0

I am trying using dup2 redirect stdout to another file:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main(void)
{
  int newfd;
  if ((newfd = open("output_file.txt", O_CREAT|O_TRUNC|O_WRONLY, 0644)) < 0) {
    exit(1);
  }
  printf("Luke, I am your...\n");
  dup2(newfd, 1);
  printf("Foobar.\n");
  return 0;
}

When the first printf prints a newline \n, Luke, I am your... will be printed to the screen and Foobar will be written to output_file.txt, if the first printf does not print a new line printf("Luke, I am your...");, both string will be written to output_file.txt. So seems printf will write the first string to a buffer when there is not a newline(\n).

What really happens underlying then ?

user2018791
  • 1,041
  • 11
  • 25
  • http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – rootkea Jan 08 '16 at 11:26

2 Answers2

4

The reason is that when you don't have a newline \n, the string printed by printf() is buffered. So the whole content of the buffer is printed to the file. This has nothing to do with second call to printf().

If you do fflush(stdout); after the first printf(), you won't see this behaviour irrespective of whether you have newline '\n in the first printf() or not. Because fflush() will clear(flush) all th output buffered until that point.

The reason for having the \n in printf() seems to work expected is because printf() is line-buffered when connected to a terminal device. So the \n triggers a flushing.

P.P
  • 106,931
  • 18
  • 154
  • 210
2

The first string is still buffered in the FD when the FD is switched out beneath it. If you need to ensure that the FD is clear before switching then call fflush(stdout) first.

Ignacio Vazquez-Abrams
  • 699,552
  • 132
  • 1,235
  • 1,283