我想知道:为什么用标准库写入文件会将您的 \n
转换为 \r\n
?它是根据 C99
的标准行为还是 MS
添加的“commidity”?如果它是标准的,按照旧的 Apple 约定 (\r)
,将 "toto\n"
写入文件 write "toto\r"
?当前的行为是为了让您可以读取 UNIX 文件但 UNIX 无法读取您的文件吗?(我喜欢阴谋论)
最佳答案
-
why does writing in a file with the standard lib converts your \n into \r\n?
是为了让代码更便携;您可以在您的程序中使用
\n
并让它在 UNIX、Windows、Mac 和(据说)其他任何东西上运行。 -
Is it standard behaviour according C99 or a "commidity" added by MS?
是的,这是标准的。
-
If it is standard, with the old Apple convention (\r), would writing "toto\n" to a file write "toto\r"?
是的,需要翻译行尾字符。
-
Is the current behaviour here so that you could read UNIX file but UNIXes could not read yours?
不,没有阴谋。
来自 C11 规范,§7.21.2 流,¶2:
… 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 标准,fprintf、fputs...在 Windows 上的功能是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19552761/