问题描述
ccc> endl
真相: endl 定义为写'\\\'到流,然后调用 flush 。
误解:您应该以文本模式打开文件,以文本形式和二进制模式打开文件写入二进制数据。
真相:文本模式首先存在,因为前一段时间有文件系统区分文本文件和二进制文件。它不再是真正的任何合理的平台,我知道。您也可以将文本写入二进制打开的文件。事实上,这是你需要的,因为它有更好的定义语义和结果在更便携的代码。请注意,POSIX 不会区分二进制和文本模式。
如何处理文本:模式并使用普通的'\\\
'。你还需要担心编码。标准化UTF-8以获得Unicode正确性。 ,而不是 wchar_t ,这在不同的平台上是不同的。
#include< stdio.h>
#include< iostream>
int main(){
_fmode = _O_BINARY;
std :: ofstream f(a.txt); //以二进制模式打开
}
或者使用任何方式。
It's been an unpleasant surprise that '\n' is replaced with "\r\n" on Windows, I did not know that. (I am guessing it is also replaced on Mac...)
Is there an easy way to ensure that Linux, Mac and Windows users can easily exchange text files?
By easy way I mean: without writing the file in binary mode or testing and replacing the end-of-line chars myself (or with some third party program/code). This issue effects my C++ program doing the text file I/O.
Sorry for partial overlap with other answers, but for the sake of completeness:
Myth: endl is 'more portable` since it writes the line ending depending on the platform convention.
Truth: endl is defined to write '\n' to the stream and then call flush. So in fact you almost never want to use it.
Misconception: You should open files in text mode to write text and in binary mode to write binary data.
Truth: Text mode exists in the first place because some time ago there were file-systems that distinguished between text files and binary files. It's no longer true on any sane platform I know. You can write text to binary-opened files just as well. In fact it's what you want to do, since it has better-defined semantics and results in more portable code. Note that POSIX does not distinguish between binary and text mode.
How to do text: Open everything in binary mode and use the plain-old '\n'. You'll also need to worry about the encoding. Standardize on UTF-8 for Unicode-correctness. Use UTF-8 encoded narrow-strings internally, instead of wchar_t which is different on different platforms. Your code will become easier to port.
Tip: You can force MSVC to open all files in binary mode by default. It should work as follows:
#include <stdio.h> #include <iostream> int main() { _fmode = _O_BINARY; std::ofstream f("a.txt"); // opens in binary mode }
Alternatively use any of the ways described here.
这篇关于便携式行尾(换行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!