开发者

Why additional \r is injected in windows?

#include <iostream>
using namespace std;
int main( int argc, char *argv[])
{
    cout << "Hello\nWorld";
}

D:\test>hw |od -c
0000000开发者_开发百科   H   e   l   l   o  \r  \n   W   o   r   l   d
0000014

Why additional \r is injected in windows(doesn't happen on linux) ?


It is a feature of Windows going back to the first days of MS-DOS. In those systems, the convention is that a line delimiter is the character pair "\r\n". Of course, in Linux/Unix/Solaris/etc., the line delimiter is the single character "\n"

There are various utilities, such as Linux's dos2unix and unix2dos which do nothing but this transformation. Virtually every file transfer program has a means of dealing with it too. See kermit's mode command.

The convention affected the MSDOS/windows C runtime library function fopen() (among others): the second parameter can have a b or t to explicitly set the line delimiter conversion. A text conversion transforms \r\n to \n on input and \n to \r\n on output. A binary conversion does no such transformation.

FILE *f1 = fopen ("somefile.txt", "rt");  /* open in text conversion mode */
FILE *f2 = fopen ("anotherfile.bin", "rb");  /* open without text conversion */


Because the output function is platform denpendent. in windows, all line break is \r\n, int constract, the linux/unix is \n


Windows, Unix and Mac all mark newlines differently.

Windows uses \r\n, Unix/Linux \n, Mac \r. Once you start dealing with text files on multiple platforms this becomes a real mess. This is why any serious text editor has an option to switch among them and why Linux has utilities like dos2unix. Try loading a Unix-style text file (with only \n) into Notepad. You'll notice it's all on one line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜