user1516425
user1516425

Reputation: 1571

Why doesn't C print to shell until newline?

In C, sometimes my output will not get printed to Terminal until I print the newline character \n. For example:

int main()
{
   printf("Hello, World");
   printf("\n");
   return 0;
}

The Hello World will not get printed until the next printf (I know this from setting a breakpoint in gdb). Can someone please explain why this happens and how to get around it?

Thanks!

Upvotes: 4

Views: 679

Answers (2)

Diego Torres Milano
Diego Torres Milano

Reputation: 69388

Additionally to fflush() you can set the buffering options with setvbuf(3).

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

This is done for performance reasons: passing data to console is too expensive (in terms of execution speed) to do it character-by-character. That is why the output is buffered until the newline is printed: characters are collected in an array until it is time to print, at which time the entire string is passed to the console. You can also force output explicitly, like this:

fflush(stdout);

Upvotes: 8

Related Questions