Search code examples
cstdoutbuffering

Setting C program to line buffer won't work


I'm trying to force my C program to line buffer (stdout is going to be captured by a java program), but it always seems to fully buffer instead. Here is some sample code:

#include <stdio.h>
#include <stdlib.h>

int main(){
    char c;
    setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
    printf("Hello world\n");
    c = getchar();
    printf("got char: %c\n", c);
}

If I specify _IOLBF or _IOFBF, then I don't see an output until I input a char. Only if I use _IONBF will I see output before the getchar(). Shouldn't _IOLBF do the same since "Hello World\n" contains a '\n'?

I am using visual c++ 2005.

Thanks


Solution

  • According to this Microsoft documentation:

    _IOLBF: For some systems, this provides line buffering. However, for Win32, the behavior is the same as _IOFBF - Full Buffering.