便携式行尾(换行) [英] Portable end of line (newline)

查看:161
本文介绍了便携式行尾(换行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

'\\\
'
取代了 / a>与\r\\\
在Windows上,我不知道。 (我猜它也在Mac上被替换了...)



有一个简单的方法来确保Linux,Mac和Windows用户可以轻松地交换文本文件?



通过简单的方式我的意思是:没有以二进制模式编写文件或者测试和替换结束字符本身第三方程序/代码)。这个问题影响我的C ++程序做文本文件I / O。

解决方案

对于与其他答案部分重叠,为了完整起见:



神话: ccc> endl

真相: endl 定义为写'\\\
'到流,然后调用 flush



误解:您应该以文本模式打开文件,以文本形式和二进制模式打开文件写入二进制数据。



真相:文本模式首先存在,因为前一段时间有文件系统区分文本文件和二进制文件。它不再是真正的任何合理的平台,我知道。您也可以将文本写入二进制打开的文件。事实上,这是你需要的,因为它有更好的定义语义和结果在更便携的代码。请注意,POSIX 不会区分二进制和文本模式。



如何处理文本:模式并使用普通的'\\\
'。你还需要担心编码。标准化UTF-8以获得Unicode正确性。
在内部使用UTF-8编码的窄字符串,而不是 wchar_t ,这在不同的平台上是不同的。

您可以强制MSVC以二进制模式打开所有文件 默认。它应该工作如下:

  #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.

这篇关于便携式行尾(换行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆