为什么不fwrite()将编写使用&QUOT二进制文件; WB&QUOT ;,在C,在Mac OS X? [英] Why doesn't fwrite() write a Binary File using "wb", in C, on Mac OS X?

查看:130
本文介绍了为什么不fwrite()将编写使用&QUOT二进制文件; WB&QUOT ;,在C,在Mac OS X?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关学习C和理解二进制文件和文本文件之间的差异的缘故,我试图写一个字符串到文件既是文件类型,像这样:

For the sake of learning C and understanding the difference between Binary Files and Text Files, I'm attempting to write a string to file as both file types like so:

char * string = "I am a string!";

FILE * filePtrA = fopen("/output.txt", "wt");
fwrite(string, strlen(string), 1, filePtrA);

FILE * filePtrB = fopen("/output.bin", "wb");
fwrite(string, strlen(string), 1, filePtrB);

fclose(filePtrA);
fclose(filePtrB);

不过两者重量WB正在写一个文本文件,其中WB应该写为二进制文件。六角出现像这样的两个文件:

However both "wt" and "wb" are writing as a Text File, where "wb" should be writing as a Binary File. Hex appears like so for both files:

49 20 61 6D 20 61 20 73 74 72 69 6E 67 21

这是怎么回事,我怎么能写的东西作为一个二进制文件?

Why is this happening, and how can I write something as a Binary File?

我已阅读,操作系统(的Mac OS X 10.6 - GCC 4.2),可能无法二进制和文本文件区分开来,但我还是难倒为什么一个十六进制编辑器也无法检测到任何区别

I have read that the OS (Mac OS X 10.6 - GCC 4.2) might not differentiate between Binary and Text Files, though I'm still stumped why a hex editor wouldn't detect any difference.

推荐答案

所有的文件是二进制的。

All files are binary.

的fopen 在的上下文中文本文件和二进制文件之间的区别在于,标准库可以使用一个过滤器用于读取和在当写入文件文本模式。在二进制模式下,你写的东西总是写的是什么。

The difference between "text files" and "binary files" in the context of fopen is that the standard library may use a filter for reading and writing the file when in text mode. In binary mode, what you write is always what is written.

我知道的唯一实际的例子是在Windows,其中以文本方式打开文件将使Windows风格的行尾(CRLF,\\ r \\ n)和C风格/ Unix风格的行结束(LF,\\ n)。例如,当您打开一个文件以文本方式阅读在Windows中,行尾会在你的程序显示为\\ n。如果您在二进制模式下打开它,行尾会显示为\\ r \\ n在程序中。

The only practical example I know of is in Windows, where opening a file in text mode will make it convert between Windows-style line endings (CRLF, "\r\n") and C-style/Unix-style line-endings (LF, "\n"). For example when you open a file for reading in Windows in text mode, line endings will appear as "\n" in your program. If you were to open it in binary mode, line endings would appear as "\r\n" in your program.

您还可以检查您的文件,例如:

You can also inspect your file with cat, for example:

猫的文件名

您应该得到的输出:<!code>我是一个字符串

这篇关于为什么不fwrite()将编写使用&QUOT二进制文件; WB&QUOT ;,在C,在Mac OS X?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆