我知道要显示的消息缓冲在 stdout
中。但是请考虑以下代码:
#include <stdio.h>
int main()
{
while(true)
{
printf("Buffered, will be flushed");
}
}
我认为在到达换行符之前不会显示消息。但在这种情况下,我们将显示消息包。
最佳答案
缓冲区的大小不是无限的。如果您输出的内容超过缓冲区的大小,它将被自动刷新,并且您会同时看到一堆消息(在此处重复)。
以下是 C 标准如何描述各种形式的缓冲(C11 草案 n1570,§7.21.3/3):
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
andsetvbuf
functions.
添加了强调。 POSIX 具有基本相同的定义,您可以在 Standard I/O Streams 中在线浏览。章。
标准输出通常是行缓冲的。
关于c - 在标准输出中缓冲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23590377/