在C中自动stdout缓冲区刷新的规则是什么? [英] What are the rules of automatic stdout buffer flushing in C?

查看:123
本文介绍了在C中自动stdout缓冲区刷新的规则是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

首先,我感到困惑的是,该伪代码不会每次都输出输出迭代:

First of all I was confused that this pseudo code doesn't print output every iteration:

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

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

But if I add newline character it will.

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

After few experiments i found that on my machine stdout buffer is flushed:


  1. 当我输入stdout 1025个字符或更多时;

  2. 当我阅读stdin时;

  3. 当我将换行符放入stdout时;

第一个条件是完全清楚的-当缓冲区已满时,应将其刷新。第二个也是合理的。但是,为什么换行符会导致冲洗呢?

The first condition is totally clear - when the buffer is full it should be flushed. The second one is also reasonable. But why newline character causes flushing? What are the others implicit conditions for this?

推荐答案

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

Rules of automatic flushing stdout buffer is implementation-defined (ID). It is ID when the stream is unbuffered, fully buffered, or line buffered.


当流未缓冲时,字符应尽快从源或目标处出现。否则,字符可能会作为块被累积并传输到主机环境或从主机环境传输。

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.

对这些特性的支持是实现定义的,... C11dr§7.21.33

Support for these characteristics is implementation-defined, ... C11dr §7.21.3 3






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

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

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

If code wants to insure output is certainly flushed, use fflush(). Other conditions that may automatically flush the stream are implementation defined.

这篇关于在C中自动stdout缓冲区刷新的规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆