3

I have a C file that looks like this:

#include <stdio.h>

int main(void)
{
   printf("Hello world\n");
   while (1);
   return 0;
}

And I would like to see "Hello world" printed in a new file. But it doesn't work when I try to redirect the standard output like this:

./hello_world >> logfile &

And then kill the program hello_world.

Zah
  • 6,394
  • 1
  • 22
  • 34

2 Answers2

2

You need to flush stdout before the loop:

#include <stdio.h>

int main(void)
{
   printf("Hello world\n");
   fflush(stdout);
   while (1);
   return 0;
}
Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
  • It works this way. However I don't understand way. I thought the `\n` in `printf` already flushed stdout as it occurs in the terminal. – Zah Nov 19 '11 at 15:14
  • 2
    Newline flushes the output directed to a terminal. Your output is directed to a regular file. – Adam Zalcman Nov 19 '11 at 15:17
0

If you want to see output as it occurs, use fflush(stdout); after your printf().

Richard Pennington
  • 19,673
  • 4
  • 43
  • 72