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

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

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

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 'text mode' 在 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.

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

本文标题为:以二进制和文本方式打开文件的区别

基础教程推荐