2

I'm trying to write a .dat file using Windows subsystem for Linux, but the fstream library seems to bypass every endline command. Here is my code:

int main()
{
   string fname = "DataSheet.dat";
   ofstream fdata (fname.c_str(), ios::out);

   fdata << "First line" << endl;
   fdata << "Second line" << endl;

   fdata.close();

   return = 0;
}

I tried substituting << endl with << "\n" and modifying the ofstream command like showed there, but nothing worked; the output was always First lineSecond line instead of First line and Second line on subsequent lines. Besides, the code works perfectly well when I print the output to video using cout command or when I compile and run it on cygwin.
Is it a problem of Windows subsystem for Linux or am I missing something important?

  • 3
    Perhaps related to https://stackoverflow.com/q/1552749/8769985 Try substituting ```<< endl``` with ```\r\n``` – francesco Apr 08 '19 at 14:29
  • 1
    How are you examining the file? Don't use any Windows program that only understands Windows newlines, like Notepad. – molbdnilo Apr 08 '19 at 14:32
  • Is this a case of creating the file on one system and viewing it on another that doesn't recognise the other CRLF , a duplicate of https://stackoverflow.com/questions/9705923/c-ofstream-line-break – newbie Apr 08 '19 at 14:47
  • @francesco it worked, thanks a lot! I peeked at the question you linked, but imho it would be great if you could answer explaining why ‘\r’ and ‘\r\n’ work in this specific case. – Francesco Arnaudo Apr 08 '19 at 14:47
  • @newbie I get your point, but why then opening with Notepad the same .dat file compiled and run first by Cygwin and then by Windows bash doesn’t give the same result? – Francesco Arnaudo Apr 08 '19 at 14:50
  • @Francesco Notepad doesn't recognise linux LF end of line character it needs a "/r" where as on linux the FOL character is recognised and displayed correctly – newbie Apr 08 '19 at 15:04

1 Answers1

1

By a comment.

Try substituting << endl with \r\n

This is due to the differences in the line endings of linux and windows. In windows you need to add a carriage return and then the new line character.
While in linux there is not need for the carriage return.

The problem comes from the fact that you are compiling for linux so std::endl places the linux version line ending but you are trying to view the output in windows.

Petar Velev
  • 2,305
  • 12
  • 24