Search code examples
cfilenewlinemsvcrt

Writing to file from stdout


I am creating an EXE, which is used with stdin and stdout streams.

The output of my executable is writing some compressed data to the stdout stream.

  int fd = fileno(stdout);
  _setmode(fd, O_BINARY);
  n = write(fd, buffer, nbytes);

But when I am re-directing to those data which are written to stdout stream, to a file,(using my_exe get_data > File.txt ), the data length in the file will be mismatching with original data.If I have a 100 character data, then in the file, I am seeing 106 chars data. I think some newline or carriage return is getting added to the file. I have set the stdout to binary stream. but while re-directing to file, the same is happening. Is there any way to solve the issue.


Solution

  • You are using _setmode a MS Visual C++ function replacing setmode which is deprecated. Yet you are using the deprecated fileno and write.

    Please use _fileno and _write.