printf 缓冲是 C 标准的一部分吗?
Is printf buffering part of the C standard?
我正在 Linux 上用 C 编写程序,其中各种内容将通过 printf
写入 stdout
。当然,我会尽量减少 IO 调用并缓冲所有信息,然后将其传递给单个打印调用。但是,通过测试,我发现 printf
会自行缓冲,直到达到 '\n'
。
我的问题是,我可以确定所有 printf
实现都这样做,还是 glibc 刚刚优化?相信 printf
为我做缓冲可靠吗?
C 标准允许非缓冲和缓冲流。相关部分是C17 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.
这通常取决于 OS 而不是标准库实现。大多数基于主机的控制台 OS 使用行缓冲实现,其中 \n
将“刷新缓冲区”。否则,对 fflush(stdout)
的显式调用将始终执行此操作(严格来说它更便携)。
无缓冲系统的一个例子是有限的“裸机”微控制器,其中 stdout
是一个 UART,没有硬件缓冲区来存储大量字符。
我正在 Linux 上用 C 编写程序,其中各种内容将通过 printf
写入 stdout
。当然,我会尽量减少 IO 调用并缓冲所有信息,然后将其传递给单个打印调用。但是,通过测试,我发现 printf
会自行缓冲,直到达到 '\n'
。
我的问题是,我可以确定所有 printf
实现都这样做,还是 glibc 刚刚优化?相信 printf
为我做缓冲可靠吗?
C 标准允许非缓冲和缓冲流。相关部分是C17 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.
这通常取决于 OS 而不是标准库实现。大多数基于主机的控制台 OS 使用行缓冲实现,其中 \n
将“刷新缓冲区”。否则,对 fflush(stdout)
的显式调用将始终执行此操作(严格来说它更便携)。
无缓冲系统的一个例子是有限的“裸机”微控制器,其中 stdout
是一个 UART,没有硬件缓冲区来存储大量字符。