windows C++ 将换行符从 CR+LF 更改为 LF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1535922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ change newline from CR+LF to LF
提问by thornate
I am writing code that runs in Windows and outputs a text file that later becomes the input to a program in Linux. This program behaves incorrectly when given files that have newlines that are CR+LF rather than just LF.
我正在编写在 Windows 中运行的代码并输出一个文本文件,该文件后来成为 Linux 程序的输入。当给定的文件具有 CR+LF 而不仅仅是 LF 换行符时,该程序的行为不正确。
I know that I can use tools like dos2unix, but I'd like to skip the extra step. Is it possible to get a C++ program in Windows to use the Linux newline instead of the Windows one?
我知道我可以使用像 dos2unix 这样的工具,但我想跳过额外的步骤。是否可以让 Windows 中的 C++ 程序使用 Linux 换行符而不是 Windows 换行符?
回答by CB Bailey
Yes, you have to open the file in "binary" mode to stop the newline translation.
是的,您必须以“二进制”模式打开文件才能停止换行转换。
How you do it depends on how you are opening the file.
您如何操作取决于您打开文件的方式。
Using fopen
:
使用fopen
:
FILE* outfile = fopen( "filename", "wb" );
Using ofstream
:
使用ofstream
:
std::ofstream outfile( "filename", std::ios_base::binary | std::ios_base::out );
回答by sbi
OK, so this is probably not what you want to hear, but here's my $0.02 based on my experience with this:
好的,所以这可能不是您想听到的,但根据我的经验,这是我的 0.02 美元:
If you need to pass data between different platforms, in the long run you're probably better off using a format that doesn't care what line breaks look like. If it's text files, users will sometimes mess with them. If by messing the line endings up they cause your application to fail, this is going to be a support intensive application.
如果您需要在不同平台之间传递数据,从长远来看,您最好使用一种不关心换行符是什么样子的格式。如果是文本文件,用户有时会弄乱它们。如果通过弄乱线路结束它们导致您的应用程序失败,这将是一个支持密集型应用程序。
Been there, done that, switched to XML. Made the support guys a lot happier.
去过那里,完成了,切换到 XML。让支持者们更开心了。