1

If I make a dup of the stdout stream (in order to use it later) and make freopen of the stdout stream to the file and then printf("data"), the file is not updated immediately with data. It is updated only after I perform fflush(stdout).

Does the fflush(stdout) have some additional side effects?

Is there some more elegant way to do this?

makes
  • 6,438
  • 3
  • 40
  • 58
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

2 Answers2

2

This is normal behavior in buffered I/O. Nothing strange should happen with a flush.

However, you shouldn't be messing with stdout in this case. Open your file with fopen, you'll get a FILE pointer. Use this pointer in functions like fprintf to print directly in it, and flush it if you need immediate results. Don't forget to close the file with fclose when you're done.

sidyll
  • 57,726
  • 14
  • 108
  • 151
1

You can use a single call to the C89 setvbuf() to avoid cluttering your code with fflush()'s. Or maybe the wrapper setlinebuf().

But all of the above just flush the buffers. You may need to use fsync().

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77