加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 04:52:28 所属栏目:百科 来源:网络整理
导读:我只是好奇应该满足哪些条件自动刷新stdout缓冲区. 首先,我很困惑这个伪代码不会在每次迭代时打印输出: while (1) { printf("Any text"); sleep(1);} 但如果我添加换行符,它会. 经过几次实验,我发现在我的机器上stdout缓冲区被刷新: 当我输入1025个字符或
我只是好奇应该满足哪些条件自动刷新stdout缓冲区.

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

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

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

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

>当我输入1025个字符或更多字符时;
>当我读到标准时;
>当我将换行符添加到stdout时;

第一个条件是完全清楚的 – 当缓冲区已满时,应该刷新它.第二个也是合理的.但为什么换行符导致潮红?其他隐含条件是什么?

解决方法

自动刷新标准输出缓冲区的规则是实现定义的(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().可以自动刷新流的其他条件是实现定义的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读