Home > Software design >  Convert .txt file from CRLF to LF and back
Convert .txt file from CRLF to LF and back

Time:09-26

I want to write a little function that takes a file as input, and writes to an output file with the following changes:

  • If the input file uses CRLF (\r\n) as EndOfLine, it should be replaced with only LF (\n).
  • If it uses LF (\n), those should be replaced with CRLF (\r\n)

See input

I get this output: output

I tried solving this by debugging my script, and what I found is that if(c == '\r') never evaluates to true, so it seems like I have no \r's in my .txt, which notepad says I do.

I am on windows, and that's the only thing I can think of that might cause this, but I don't know how. (Also, sorry for the bad formatting, I couldn't get it to look better with the images)

CodePudding user response:

When you open a file in text mode, the input stream will already convert line endings. Open the file in binary mode if you want full control.

input.open(location, std::ios::binary);
output.open(location, std::ios::binary);
  • Related