以二进制文件和文本文件打开文件的区别

2022-01-09 00:00:00 file binary text c++

我做过一些类似的事情:

I've done some stuff like:

FILE* a = fopen("a.txt", "w");
const char* data = "abc123";
fwrite(data, 6, 1, a);
fclose(a);

然后在生成的文本文件中,它像预期的那样显示abc123".但后来我做到了:

and then in the generated text file, it says "abc123" just like expected. But then I do:

//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);

并得到完全相同的结果.如果我使用二进制或普通模式读取文件,它也会给我相同的结果.所以我的问题是,使用或不使用二进制模式的 fopen 有什么区别.

and get the exact same result. If I read the file using binary or normal mode, it also gives me the same result. So my question is, what is the difference between fopening with or without binary mode.

我在哪里读到了 fopen 模式:http://www.cplusplus.com/reference/cstdio/fopen/

Where I read about fopen modes: http://www.cplusplus.com/reference/cstdio/fopen/

推荐答案

您提供的链接确实描述了差异,但它隐藏在页面底部:

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

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.

转换可能是将 规范化为 (反之亦然),或者可能忽略 0x7F 以外的字符(a-la '文本模式' 在 FTP 中).就我个人而言,我会以二进制模式打开所有内容,并使用良好的 Unicode 或其他文本编码库来处理文本.

The conversion could be to normalize to (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good Unicode or other text-encoding library for dealing with text.

相关文章