0

Sample C++ program:

#include <iostream>
#include <fstream>    
int main(int argc, char* argv[]) {
    if (argc > 1) {
        std::ofstream output(argv[1]);
        output << "Line 1\nLine 2\n" << std::flush;
    } else {
        std::cout << "Line 1\nLine 2\n" << std::flush;
    }
}

Direct output (Windows 7):

TestProgram.exe direct.txt

yields

Line 1[LF]
Line 2[LF]

Redirected output:

Testprogram.exe >redir.txt

yields

Line 1[CR][LF]
Line 2[CR][LF]
  1. Where are the line endings being overwritten? cout? Console? Somewhere in between? And why?
  2. Is there anything I can do about it? I've tried setting the binary flag on std::cout but that didn't change anything.

ETA: Using echo+redirection I can send a LF character to a file, using

echo line 1◙line 2 >echo.txt

(where the LF character is made with Alt-10 on the keypad). So it seems to be a C++ problem.

chessbot
  • 436
  • 2
  • 11
  • I would guess the terminal absorbed the LR and the CR. The CR probably returned the caret to the beginning of the line and the LF would have cause it to scroll down one. – Galik Oct 16 '14 at 15:52
  • How did you set the binary flag? – David G Oct 16 '14 at 16:18
  • `std::cout.setf(std::ios::binary);` Can't set it at creation time on `cout`, unless there's some way to close and reopen it. – chessbot Oct 16 '14 at 16:19
  • `std::ios_base::binary` is an `openmode` flag, not a format flag. You can't set `std::cout` for binary output. – David G Oct 16 '14 at 16:21
  • Yep, that would be why it didn't work. – chessbot Oct 16 '14 at 16:25
  • On Windows, line endings are converted to `\n\r`. I'm not sure how to prevent it though. – David G Oct 16 '14 at 16:28
  • Yeah, I noticed :-) The other part of the question is, what's doing the converting? Is it internal to C++ when writing to cout or something about redirection? – chessbot Oct 16 '14 at 16:35
  • 1
    @chessbot: It's converted inside the stream. `std::cout` always converts, `std::ofstream` converts or not depending on mode passed to constructor/`open`. But I always thought the default is to convert as well. At least in the C API (`fopen`) it is. – Jan Hudec Oct 16 '14 at 16:44
  • @JanHudec Yeah, that's what the echo test seems to support. Do you know if there's any way to change that behavior on `cout`? – chessbot Oct 16 '14 at 16:51
  • @0x499602D2: `\r\n`. – Lightness Races in Orbit Oct 16 '14 at 17:35

0 Answers0