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

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.

这篇关于以二进制文件和文本文件打开文件的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)