The stdout stream is line buffered by default, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:

  • Print to stderrinstead using fprintf (stderr is unbuffered by default):

    fprintf(stderr, "I will be printed immediately");
    
  • Flush stdout whenever you need it to using fflush:

    printf("Buffered, will be flushed");
    fflush(stdout); // Will now print everything in the stdout buffer
    
  • Disable buffering on stdout by using setbuf:

    setbuf(stdout, NULL);
    
  • Or use the more flexible setvbuf:

    setvbuf(stdout, NULL, _IONBF, 0); 
    
Answer from Rudd Zwolinski on Stack Overflow
Top answer
1 of 10
943

The stdout stream is line buffered by default, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:

  • Print to stderrinstead using fprintf (stderr is unbuffered by default):

    fprintf(stderr, "I will be printed immediately");
    
  • Flush stdout whenever you need it to using fflush:

    printf("Buffered, will be flushed");
    fflush(stdout); // Will now print everything in the stdout buffer
    
  • Disable buffering on stdout by using setbuf:

    setbuf(stdout, NULL);
    
  • Or use the more flexible setvbuf:

    setvbuf(stdout, NULL, _IONBF, 0); 
    
2 of 10
160

No, it's not POSIX behaviour, it's ISO C behaviour (well, it is POSIX behaviour but only insofar as they conform to ISO C).

Standard output is line buffered if it can be detected to refer to an interactive device, otherwise it's fully buffered. So there are situations where printf won't flush, even if it gets a newline to send out, such as:

myprog >myfile.txt

This makes sense for efficiency since, if you're interacting with a user, they probably want to see every line. If you're sending the output to a file, it's most likely that there's not a user at the other end (though not impossible, they could be tailing the file). Now you could argue that the user wants to see every character but there are two problems with that.

The first is that it's not very efficient. The second is that the original ANSI C 89 mandate was to primarily codify existing behaviour, rather than invent new behaviour, and those design decisions were made long before ANSI started the process. Even ISO C nowadays treads very carefully when changing existing rules in the standards.

As to how to deal with that, if you fflush (stdout) after every output call that you want to see immediately, that will solve the problem.

Alternatively, you can use setvbuf before operating on stdout, to set it to unbuffered and you won't have to worry about adding all those fflush lines to your code:

setvbuf (stdout, NULL, _IONBF, BUFSIZ);

Just keep in mind that may affect performance quite a bit if you are sending the output to a file. Also keep in mind that support for this is implementation-defined, not guaranteed by the standard.

ISO C99 section 7.19.3/3 is the relevant bit:

When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block.

When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled.

When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered.

Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment.

Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.

🌐
George Washington University
www2.seas.gwu.edu › ~simhaweb › C › modules › appendix › misc › misc.html
Using fflush() to force output
int main () { int A[10]; int *B; int i; printf ("Before first for-loop\n"); fflush (stdout); for (i=0; i<10; i++) { A[i] = 1; } printf ("After first for-loop\n"); fflush (stdout); for (i=0; i<10; i++) { B[i] = A[i]; } printf ("After second for-loop\n"); fflush (stdout); } Upon compilation and execution, we see the following output: % gcc -o flush flush.c % flush Before first for-loop After first for-loop Segmentation fault (core dumped) Now we know the seg-fault occurs in the second loop.
Discussions

When does `Printf.printf` flush?
I understand I can force flushing to occur by suffixing my string with the special format arg %! Printf.printf "--> LOG: [%s]\n%!" some_var If I understand things correctly, this is equivalent to: Printf.printf "--> L… More on discuss.ocaml.org
🌐 discuss.ocaml.org
13
0
May 1, 2023
Flush buffer created by printf retargeting
When I override the console, I see no way of flushing the buffer created by using printf. For example, if I override the console with a BufferedSerial, printf statements without a line break in them are not flushed. They only are printed when printf is called with a line break. More on forums.mbed.com
🌐 forums.mbed.com
2
1
February 10, 2022
Flushing buffers in C - Stack Overflow
Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. More on stackoverflow.com
🌐 stackoverflow.com
Printf flushing
I haven’t read the standards in a while, but I don’t think there’s anything that forbids the buffers to flush at any time. The library can flush whenever it wants, and flushing right before a sleep is very user friendly. Edit: Don’t rely on this behavior, though. More on reddit.com
🌐 r/C_Programming
18
1
June 24, 2018
🌐
Reddit
reddit.com › r/c_programming › a call to write() prevents the flushing of printf() buffer
r/C_Programming on Reddit: A call to write() prevents the flushing of printf() buffer
March 19, 2024 -

I ran into an interesting behaviour that I can't seem to find a complete answer to when I searched..

Let's say I have this piece of code:

    do {

        printf("HEY! ");

    } while (1);

If this is run as part of a program executed in the terminal, it would just print on the terminal screen forever. However... if I add this to the code:

    do {

        printf("HEY! ");
        // read a single character into c
        read(STDIN_FILENO, &c, 1);

    } while (1);

Suddenly printf buffer will never flush and therefore never print to the screen. Additionally, if I add one more line:

   do {

        printf("HEY! ");
        // read a single character into c
        read(STDIN_FILENO, &c, 1);
        buffer[0] = c;
        // write the read character to standard output
        write(STDOUT_FILENO, b, 1);

    } while (1);

The read-in character will be sent to stdout and will be outputted to the screen each time a key is pressed. However, in this case the printf() local buffer will still never flush to the screen.

In fact it seems that as long as I have a call to read() anywhere in the function printf() will do nothing no matter where I have placed it in the function code (above or below). The only way I can get it to flush is it I make the explicit call fflush(stdout).

So I have two questions:

  1. Why is this behaviour happening, or in other words, what exactly (implicitly) causes the printf() buffer to flush? What causes this to not happen once a call to read() is made?

  2. Why does a call to fflush(stdout) flush the buffer of print()? Is this buffer not local to the function, which then would not cause it to flush when we explicitly flush stdout?

🌐
Quora
quora.com › Why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-string-Is-this-POSIX-behavior-How-might-you-have-printf-immediately-flush-every-time
Why does printf not flush after the call unless a newline is in the format string? Is this POSIX behavior? How might you have printf immediately flush every time? - Quora
Answer (1 of 5): This isn’t really about [code ]printf[/code] per se—it applies to anything you write to stdout, whether using [code ]printf[/code] or [code ]putc[/code], [code ]puts[/code], [code ]fputs[/code], etc. Basically, if [code ]stdout[/code] refers to some non-interactive stream ...
🌐
Delft Stack
delftstack.com › home › howto › flush stdout in c
How to Flush stdout Output Stream in C | Delft Stack
March 12, 2025 - In this example, calling setbuf(stdout, NULL) disables buffering for the stdout stream. As a result, every call to printf will display output immediately.
🌐
Educative
educative.io › answers › what-is-fflush-in-c
What is fflush in C?
The fflush function in C is used to immediately flush out the contents of an output stream.
Find elsewhere
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 461190 › flushing-out-from-printf-without-waiting-for-newline
c - flushing out from printf without waiting ... [SOLVED] | DaniWeb
August 19, 2013 - It doesn't get written to output until either some time has passed, or the buffer is full. To ensure that output to stdout is printed immediately, then you need to call the fflush(stdout) function after the fprintf(stdout,...), or printf() function.
🌐
Mbed OS
forums.mbed.com › mbed os
Flush buffer created by printf retargeting - Mbed OS - Arm Mbed OS support forum
February 10, 2022 - When I override the console, I see no way of flushing the buffer created by using printf. For example, if I override the console with a BufferedSerial, printf statements without a line break in them are not flushed. They only are printed when printf is called with a line break.
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 90021-flush-stdout.html
flush stdout?
May 19, 2007 - All problems in computer science can be solved by another level of indirection, except for the problem of too many layers of indirection. – David J. Wheeler ... not exactly before printf... i said before printf to make the question more understandable for what i'm trying to do...
Top answer
1 of 1
133

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_fflush.htm
C Library - fflush() function
#include <stdio.h> int main() { FILE *file1 = fopen("example3_1.txt", "w"); FILE *file2 = fopen("example3_2.txt", "w"); if (file1 == NULL || file2 == NULL) { perror("Failed to open file"); return 1; } fprintf(file1, "Data for file 1.\n"); fprintf(file2, "Data for file 2.\n"); // Flush all open output streams fflush(NULL); fclose(file1); fclose(file2); return 0; } After execution of above code,it writes different data to two files and uses fflush(NULL) to flush all open output streams, ensuring all data is written to disk before closing the files.
🌐
Narkive
microsoft.public.vc.language.narkive.com › UULgHSF4 › how-to-force-an-immediate-writing-of-the-printf-buffer-content-to-console
How to force an immediate writing of the printf() buffer content to console ???
Could someone help me ? Thank you Peter ... Post by Peter Smirnov As far as I remember there is a function like flush() or so which has a similar meaning. Try fflush(stdout); for standard output. -- Regards, Kobi Ben Tzvi · Post by Peter Smirnov I wrote something with printf() to the console (under Windows) in a DLL.
🌐
Scaler
scaler.com › home › topics › fflush() in c
fflush() in C - Scaler Topics
May 4, 2023 - In this example, we are going to use the flush() function of the C programming language to print the data of buffered memory on the console without using the end-line character (\n). As the printf() function of C is a buffered function means data given as output by this function is first to go to the buffer rather than going to the console or the main file.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › use-fflushstdin-c
Use of fflush(stdin) in C - GeeksforGeeks
September 15, 2023 - // C program to illustrate flush(stdin) // This program works as expected only // in certain compilers like Microsoft // visual studio. #include <stdio.h> #include<stdlib.h> int main() { char str[20]; int i; for (i = 0; i<2; i++) { scanf("%[^\n]s", str); printf("%s\n", str); // used to clear the buffer // and accept the next string fflush(stdin); } return 0; } Input: geeks geeksforgeeks ·
🌐
Medium
medium.com › @sreehema2025 › understanding-buffers-in-c-why-your-printf-might-not-show-up-immediately-98c4d9d60d75
Understanding Buffers in C: Why Your printf() Might Not Show Up Immediately | by Sree Hema | Medium
August 3, 2025 - Newline character (\n) is found Especially for stdout , the buffer flushes when you hit a newline. → printf(“Hello\n”);works instantly.
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › c › FIO23-C.+Do+not+exit+with+unflushed+data+in+stdout+or+stderr
FIO23-C. Do not exit with unflushed data in stdout or stderr - SEI CERT C Coding Standard - Confluence
The C standard makes no guarantees as to when output to stdout (standard output) or stderr (standard error) is actually flushed. On many platforms, output to stdout is buffered unless stdout outputs to a terminal, and stderr output is typically not buffered. However, programs are free to modify the buffering rules for either stdout or stderr.