Difference between opening a file in binary vs text(以二进制文件和文本文件打开文件的区别)
问题描述
我做过一些类似的事情:
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.
这篇关于以二进制文件和文本文件打开文件的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:以二进制文件和文本文件打开文件的区别
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
