3

The following C++ code:

ofstream out("File.txt");
const char *str = "0\r\n1\r\n2\r\n";
out << str;

Creates following file (File.txt above):

File.txt content

Why is there extra CR's and LF's? My platform is Windows 7 and compiler VS 2013.

The situation above will cause problem with another of my program that will parse this file line by line and that program assumes that every line will contain data. I could remove empty lines but I want to understand why when str is saved, there are extra CR's and LF's.

Donotalo
  • 12,748
  • 25
  • 83
  • 121
  • 2
    There are no extra LF's, only CR's. – user229044 Mar 17 '15 at 03:32
  • 1
    If you open the file in text mode it will translate `\n` to `\r\n` since that is the correct line ending for Windows. If you don't want that, open the file in binary mode. – Retired Ninja Mar 17 '15 at 03:32
  • Windoze likes a multi-character line terminator for some reason. Probably just to make our lives more complex. – jschultz410 Mar 17 '15 at 03:33
  • @jschultz410, that is the correct line ending for a line printer, where this came from. You need both a new line and a carriage return to start a new line. – Blindy Mar 17 '15 at 03:35
  • @Blindy I wonder why unix went a different way? Probably because of the extra complication a multi-character line terminator commonly adds versus the extremely rare benefit where you really do want to keep the current line offset but move down one line. – jschultz410 Mar 17 '15 at 03:38

1 Answers1

3

\n outputs the platform-specific newline, in this case each \n is written as a \r\n. You do not need to manually add your own \r, that is the source of the duplication.

user229044
  • 232,980
  • 40
  • 330
  • 338