Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C print to shell until newline?

Tags:

c

linux

shell

macos

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!

like image 584
user1516425 Avatar asked Dec 16 '22 12:12

user1516425


2 Answers

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);
like image 183
Sergey Kalinichenko Avatar answered Dec 28 '22 23:12

Sergey Kalinichenko


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

like image 44
Diego Torres Milano Avatar answered Dec 29 '22 00:12

Diego Torres Milano