在 Windows 中,当您以文本模式从文件(或标准输入)读取字符 \r\n
时,\r
被删除,您只能读取 \n
.
是否有一个标准应该如此?
我能确定这对 Windows 上的任何编译器都是正确的吗?在那些平台上,其他特定于平台的字符组合也会被替换为 \n
吗?
最佳答案
是的,这来自与 C 的兼容性。在 C 文本流中,行由换行符终止。这是程序看到的文本流的内部表示。 I/O 库在内部表示和一些外部表示之间进行转换。
内部表示与平台无关,而文本有不同的特定于平台的约定。这就是在流库中使用文本模式的意义所在;可以编写可移植的文本操作程序,这些程序不必包含一堆 #ifdef
指令即可在不同平台上工作,或者构建自己的独立于平台的文本抽象。
碰巧 C 文本流的内部表示与文本文件的 native Unix 表示相匹配,因为 C 语言及其库起源于 Unix。为了将 C 程序移植到其他平台,添加了文本流抽象,使非 Unix 系统上的文本文件看起来像 Unix 文本文件。
在 ISO/IEC 9899:1999 标准(“C99”)中,我们有这个:
7.19.2 Streams
[...]
A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one-to-one correspondence between the characters in a stream and those in the external representation.
大胆强调我的。 C++ 流是根据 C 流定义的。在 C++ 标准中没有对文本模式与二进制模式的解释,除了一个表,该表将各种流模式标志组合映射到适合作为 fopen
的模式参数的字符串。
关于c++ - 为什么 CR LF 在 Windows 中被更改为 LF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17371695/