二进制流有何特别之处?
std::fstream
可以选择将流视为二进制而不是文本。有什么区别?
据我所知,这完全取决于该文件在其他程序中的打开方式。如果我将 A
写入二进制流,它只会转换为 01000001
(65,A
的 ASCII 代码) - 确切的相同的表示。它可以在文本编辑器中读作字母“A”,或者在其他程序中读作二进制序列01000001
。
我是否遗漏了一些东西,或者流是否被视为二进制没有任何区别?
std::fstream
has the option to consider streams as binary, rather than textual. What's the difference?
As far as I know, it all depends on how the file is opened in other programs. If I write A
to a binary stream, it'll just get converted to 01000001
(65, A
's ASCII code) - the exact same representation. That can be read as the letter "A" in text editors, or the binary sequence 01000001
for other programs.
Am I missing something, or does it not make any difference whether a stream is considered binary or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在文本流中,换行符可以与
\n
字符相互转换;对于二进制流,这种情况不会发生。原因是不同的操作系统对于存储换行符有不同的约定; Unix 使用\n
,Windows\r\n
,老式 Mac 使用\r
。对于使用文本流的 C++ 程序,这些都显示为\n
。In text streams, newline characters may be translated to and from the
\n
character; with binary streams, this doesn't happen. The reason is that different OS's have different conventions for storing newlines; Unix uses\n
, Windows\r\n
, and old-school Macs used\r
. To a C++ program using text streams, these all appear as\n
.在 Linux/Unix/Android 上没有区别。
在 Mac OS/X 或更高版本上没有区别,但我认为较旧的 Mac 可能会在读取时将“\n”更改为“\r”,并且写入时反转(仅适用于文本流)。
在 Windows 上,对于文本流,某些字符会受到特殊处理。 '\n' 字符写为“\r\n”,“\r\n”对读为“\n”。 '\0x1A' 字符被视为“文件结尾”并终止读取。
我认为 Symbian PalmOS/WebOS 的行为与 Windows 相同。
二进制流只是写入字节,不会在任何平台上进行任何转换。
On Linux/Unix/Android there is no difference.
On a Mac OS/X or later there is no difference, but I think older Macs might change an '\n' to an '\r' on reading, and the reverse on writing (only for a Text stream).
On Windows, for a text stream some characters get treated specially. A '\n' character is written as "\r\n", and a "\r\n" pair is read as '\n'. An '\0x1A' character is treated as "end of file" and terminates reading.
I think Symbian PalmOS/WebOS behave the same as Windows.
A binary stream just writes bytes and won't do any transformation on any platform.
反过来说,它是特殊的文本流,特别是因为
\n
转换为\n
或\r\n (甚至
\r
..) 取决于您的系统。You got it the other way around, it's text streams that are special, specifically because of the
\n
translation to either\n
or\r\n
(or even\r
..) depending on your system.实际的区别在于 Microsoft 操作系统上对行结束序列的处理。
二进制流精确地返回文件中存储的数据。文本流规范行结束序列,将其替换为
'\n'
。The practical difference is the treatment of line-ending sequences on Microsoft operating systems.
Binary streams return the data in the file precisely as it is stored. Text streams normalize line-ending sequences, replacing them with
'\n'
.如果您将其作为文本打开,则 C 或 C++ 运行时将根据主机(Windows 或 Linux)执行换行转换。
If you open it as text then the C or C++ runtime will perform newline conversions depending on the host (Windows or linux).