Search code examples
cprintfflush

How can I print a string with newline without flushing the buffer?


When I do this (note the included \n):

printf("Something.\n");

I would like it not to flush the buffer. I would like to manually flush it later.
Is this possible?

This question sort of asks the same thing, but asks about C++ instead of C. I don't see how I could gather how to do this in C by reading the answers to that question (so it's not a duplicate).


Solution

  • As explained in the comments, setvbuf can be used to change the buffering of any file stream, including stdout.

    Here is a simple example:

    #include <stdio.h>
    #include <unistd.h>
    
    int main(void)
    {
        setvbuf(stdout, NULL, _IOFBF, 0);
        printf("hello world\n");
        sleep(5);
    }
    

    The example uses setvbuf to make stdout fully buffered. Which means it will not immediately output upon encountering a newline. The example will only display the output after the sleep (flush on exit). Without the setvbuf the output will be displayed before the sleep.