我做过一些事情,比如:
FILE* a = fopen("a.txt", "w");
const char* data = "abc123";
fwrite(data, 6, 1, a);
fclose(a);
然后在生成的文本文件中,它像预期的那样显示“abc123”。但后来我做了:
//this time it is "wb" not just "w"
FILE* a = fopen("a.txt", "wb");
const char* data = "abc123";
fwrite(data, 6, 1, a);
fclose(a);
并得到完全相同的结果。如果我使用二进制或普通模式读取文件,它也会给我相同的结果。所以我的问题是,使用或不使用二进制模式的 fopening 有什么区别。
我在哪里读到有关 fopen 模式的信息:http://www.cplusplus.com/reference/cstdio/fopen/
您提供的链接确实描述了差异,但它隐藏在页面底部:
http://www.cplusplus.com/reference/cstdio/fopen/
Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.
转换可能是将 \r\n
规范化为 \n
(反之亦然),或者可能忽略超过 0x7F 的字符(a-la '文本模式' 在 FTP 中)。就个人而言,我会以二进制模式打开所有内容,并使用良好的 Unicode 或其他文本编码库来处理文本。