且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在基于MFC对话框的应用程序中写入文本文件

更新时间:2023-11-19 22:17:28

由于您正在文件中写入整个结构,因此该结构以字节序列而不是字符串/文本的形式进入文件.例如,如果将int(4字节)写入文件,则不会看到整数的实际值,而是一些奇怪的值.不用担心,您不必担心.读取整数(按字节顺序)时,可以正确获取整数.
简而言之,无论整数值如何,您都要写入4个字节.然后读取4个字节,就可以得到int的值.


同样,您正在编写整个结构(28字节),您肯定会看到这些字符.当您读取相同结构的28字节序列并将其类型转换为相同结构时,您将获得相同的值!

您应该使用memset/ZeroMemory将结构设置为null以获得清晰的图片.在Visual Studio中(在BINARY EDITOR中)打开文件.
Since you are writing whole structure in file, the structure goes into file as sequence of bytes, not as string/text. For example if you write an int (4-byte) into file, you will NOT see the actual value of integer, but some bizarre value. Dont worry, and you need not to worry. When you read the integer, in sequence-of-bytes form, you get your integer properly.
In short, you write 4 bytes, irrespective of the value of integer. Then you read 4-bytes, and you get value in int.


Similarly, you are writing the whole structure (which is 28 bytes), you''d definitely see those characters. When you read the same structure are sequence of 28-bytes, and typecast into same structure, you''d get the same values!

You should set the structure to null,with memset/ZeroMemory to get the clear picture. Open file in Visual Studio (in BINARY EDITOR).


如果您需要将数值写为人类可读的文本,则可以使用CStringCStdioFile类,例如实例:
If you need to write the numeric values as human-readable text than you may use use CString and CStdioFile classes, for instance:
CStdioFile file_object(filepath,CFile::modeCreate|CFile::modeWrite);
CString sValue;
sValue.Format(_T("%f"), myfile.version_number);
file_object.WriteString(","); // field separator
file_object.WriteString(myfile.name);
file_object.WriteString(","); // field separator
sValue.Format(_T("%d"), myfile.n_tcp);
file_object.WriteString("\n"); // record separator
...


:)