21

I am writing code that runs in Windows and outputs a text file that later becomes the input to a program in Linux. This program behaves incorrectly when given files that have newlines that are CR+LF rather than just LF.

I know that I can use tools like dos2unix, but I'd like to skip the extra step. Is it possible to get a C++ program in Windows to use the Linux newline instead of the Windows one?

thornate
  • 4,202
  • 9
  • 36
  • 42

2 Answers2

31

Yes, you have to open the file in "binary" mode to stop the newline translation.

How you do it depends on how you are opening the file.

Using fopen:

FILE* outfile = fopen( "filename", "wb" );

Using ofstream:

std::ofstream outfile( "filename", std::ios_base::binary | std::ios_base::out );
CB Bailey
  • 648,528
  • 94
  • 608
  • 638
  • 1
    Agreed. Open the stream as binary, and no translation takes place. the output of either '\n' or std::endl to such a stream results in a line-feed only. – Clifford Oct 08 '09 at 08:39
  • The `std::ios_base::out` flag doesn't seem to be necessary since it's implied by the `o` in `ofstream`. From the [docs](http://www.cplusplus.com/reference/fstream/ofstream/ofstream): "`out` is always set for `ofstream` objects (even if explicitly not set in argument mode)". – Gumby The Green Jul 27 '19 at 22:27
-1

OK, so this is probably not what you want to hear, but here's my $0.02 based on my experience with this:

If you need to pass data between different platforms, in the long run you're probably better off using a format that doesn't care what line breaks look like. If it's text files, users will sometimes mess with them. If by messing the line endings up they cause your application to fail, this is going to be a support intensive application.

Been there, done that, switched to XML. Made the support guys a lot happier.

sbi
  • 204,536
  • 44
  • 236
  • 426