Is stdout line buffered, unbuffered or indeterminate by default?

前端 未结 1 1535
轮回少年
轮回少年 2020-11-22 15:43

Section 7.9.13/7 of c99 states that:

At program start-up, three text streams are predefined and need not be opened explicitly -

相关标签:
1条回答
  • 2020-11-22 16:05

    The C99 standard does not specify if the three standard streams are unbuffered or line buffered: It is up to the implementation. All UNIX implementations I know have a line buffered stdin. On Linux, stdout in line buffered and stderr unbuffered.

    As far as I know, POSIX does not impose additional restrictions. POSIX's fflush page does note in the EXAMPLES section:

    [...] The fflush() function is used because standard output is usually buffered and the prompt may not immediately be printed on the output or terminal.

    So the remark that you add fflush(stdout); is correct.


    An alternative could be to make stdout unbuffered:

    setbuf(stdout, NULL);
    /* or */
    setvbuf(stdout, NULL, _IONBF, 0);
    

    But as R. notes you can only do this once, and it must be before you write to stdout or perform any other operantion on it. (C99 7.19.5.5 2)


    I just read a recent thread on comp.lang.c about the same thing. One of the remarks:

    Unix convention is that stdin and stdout are line-buffered when associated with a terminal, and fully-buffered (aka block-buffered) otherwise. stderr is always unbuffered.

    0 讨论(0)
提交回复
热议问题