gpt4 book ai didi

c - C 中自动 stdout 缓冲区刷新的规则是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 04:15:46 25 4
gpt4 key购买 nike

我只是好奇应该满足哪些条件才能自动刷新 stdout 缓冲区。

首先,我很困惑这个伪代码不会在每次迭代时都打印输出:

while (1) {
printf("Any text");
sleep(1);
}

但如果我添加换行符,它就会。

经过几次实验,我发现在我的机器上 stdout 缓冲区被刷新了:

  1. 当我向标准输出输入 1025 个或更多字符时;
  2. 当我读取标准输入时;
  3. 当我将换行符输入标准输出时;

第一个条件是完全清楚的——当缓冲区已满时,它应该被刷新。第二个也是有道理的。但是为什么换行符会导致刷新?其他隐含条件是什么?

最佳答案

自动刷新标准输出缓冲区的规则是实现定义的 (ID)。它是流未缓冲完全缓冲行缓冲时的 ID。

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, ... C11dr §7.21.3 3


I'm just curious which conditions should be satisfied to flush stdout buffer automatically.

如果代码想要确保输出肯定被刷新,请使用 fflush()。其他可能自动刷新流的条件是实现定义的。

关于c - C 中自动 stdout 缓冲区刷新的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52574870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com