c++ - 以二进制文件打开文件与以文本文件打开文件之间的区别

标签 c++ file text binary

<分区>

我做过一些事情,比如:

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 或其他文本编码库来处理文本。

关于c++ - 以二进制文件打开文件与以文本文件打开文件之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20863959/

相关文章:

C++:将整数转换为罗马数字的困惑

c++ - 相当于 mac 的 windows.h

c++ - 我希望我的继承类具有相同的构造函数

c - 向文本文件写入 1024 字节时,文本文件变成二进制文件 (linux)

react-native - 响应字体缩放的 native 最大值

c++ - 打破工厂模式中的循环依赖

database - 对于我创建的新创建的 PostgreSQL 模式,我应该使用什么正确的文件扩展名?

Python文件缓存

html - 如何使这两个带有文本响应的 div?

ios - 如何将绘制的文本移动到 UIView 的顶部?