文件访问中的文本和二进制模式有什么区别? [英] Is there any difference between text and binary mode in file access?

查看:134
本文介绍了文件访问中的文本和二进制模式有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我以文本模式而不是二进制模式打开文件,是否有区别?因为我读过UNIX和Linux没有区分文本和二进制文件。

解决方案

Linux上没有区别在本地文件系统,如Ext4和大多数其他文件系统上,也可以使用通常的GNU libc。)

也许一些奇怪的文件系统可能有一个特定的标志来打开不同的二进制或文本文件。我不知道这样的文件系统。也许你可以编写一些 FUSE 文件系统来作出区分,也许还有一些额外的 fopen 在一个奇怪的自定义libc里面



然而, C99标准(至少第271页,n1256草案的第7.19.5.3节)明确指出了文本与二进制模式,所以你的程序将更容易移植到其他系统(如Windows)如果它符合标准。

所以我的意思是,你可能想尝试传递一个模式字符串 fopen 区分二进制文本模式和文本模式。 (我同意我不经常这样做)。它不会受到伤害。



Linux


模式字符串也可以包含字母' b'或者作为最后的
字符,或者作为上述任何一个
字符串中的字符之间的字符。这是严格的与C89的
兼容性,并没有任何影响;在所有
POSIX符合系统(包括Linux)上忽略'b'。 (其他系统可能会以不同的方式处理
文本文件和二进制文件,如果您对二进制文件执行I / O操作,并且希望程序
添加b,则可能是
的好主意可能会移植到非UNIX环境中。)

当然, open(2)系统调用没有任何方式传输模式标志。 (你需要一些 private ioctl(2 )可能)


Is there any difference if I open a file in text mode rather than binary mode? Because I read that UNIX and Linux make no distinction between text and binary files.

解决方案

There is no difference on Linux (at least on native file systems like Ext4 and on most other file systems too, with the usual GNU libc).

Perhaps some bizarre filesystems could have a specific flag to open differently binary or text files. I know no such filesystem. Maybe you could code some FUSE filesystem making the distinction, perhaps with some additional hack around fopen inside a bizarrely customized libc

However, C99 standard (at least page 271, §7.19.5.3 of n1256 draft) mentions explicitly the text vs binary mode, so your program would be easier to port to other systems (such as Windows) if it conforms to the standard.

So my point is that you might want to try passing a mode string to fopen which differentiate the binary vs text mode. (I agree that I don't do that very often). It won't hurt.

The Linux fopen(3) man page explicitly says:

The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two- character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.)

Of course, the open(2) syscall does not have any way of transmitting a mode flag. (You 'll need some private ioctl(2) probably)

这篇关于文件访问中的文本和二进制模式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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