printf not working?

Sometimes we noticed that printf will only flush after there is a newline in the print string, this behavior is caused by stdout stream buffer, which is line buffered by default. This behavior has been mentioned in ISO C99 standard:

There are few options to make it to print immediately once you called it.

Option 1: fflush

1
2
printf("test");
fflush(stdout);

fflush will flush stdout immediately.

Option 2: setbuf

1
2
setbuf(stdout, NULL);
printf("test");

setbuf(stdout, NULL); will disable stdout buffering.

It also have a secure version:

1
setvbuf (stdout, NULL, _IONBF, BUFSIZ);

Reference