48

I want to turn off the buffering for the stdout for getting the exact result for the following code

while(1) {
    printf(".");
    sleep(1);
}

The code printf bunch of '.' only when buffer gets filled.

3

5 Answers 5

124

You can use the setvbuf function:

setvbuf(stdout, NULL, _IONBF, 0);

Here're some other links to the function.

2
  • 7
    Good one. Thx. By the way setbuf(stream, NULL); is equivalent to setvbuf(stream, NULL, _IONBF, BUFSIZ);
    – sehe
    Oct 24, 2011 at 14:02
  • 18
    One caveat: It's only legal to call setbuf or setvbuf as the very first operation on a stream before any input or output is performed on it. Thus using fflush explicitly is usually a better idea. Oct 24, 2011 at 14:56
23

You can also use setbuf

setbuf(stdout, NULL);

This will take care of everything

2
  • 1
    this is not a very good answer, quoting Newlib: Both ANSI C and the System V Interface Definition (Issue 2) require <<setbuf>>. However, they differ on the meaning of a <<NULL>> buffer pointer: the SVID issue 2 specification says that a <<NULL>> buffer pointer requests unbuffered output. For maximum portability, avoid <<NULL>> buffer pointers.
    – MightyPork
    Mar 4, 2016 at 23:16
  • 2
    @MightyPork Newlib is just flat-out wrong. The POSIX 2 specification for setbuf() states: "setvbuf(stream, buf, _IONBF, BUFSIZ) if buf is a null pointer." _IONBF means unbuffered Both POSIX 7 and the C standard all agree, and have agreed for decades. Feb 13, 2020 at 22:00
-3

Use fflush(FILE *stream) with stdout as the parameter.

http://www.elook.org/programming/c/fflush.html

1
  • 3
    This does not turn off buffering, it flushes the buffer once. Oct 8, 2020 at 14:23
-4

You can do this:

write(1, ".", 1);

instead of this:

printf(".");
1
-14

Use fflush(stdout). You can use it after every printf call to force the buffer to flush.

1
  • 51
    This does not really "turn off buffering of stdout in C".
    – hagello
    Dec 17, 2014 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.