gpt4 book ai didi

stdout - 默认情况下,stdout 行是缓冲的、无缓冲的还是不确定的?

转载 作者:行者123 更新时间:2023-12-01 20:27:06 29 4
gpt4 key购买 nike

c997.19.3/7 节指出:

At program start-up, three text streams are predefined and need not be opened explicitly - standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output).

As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

所以这是有道理的。如果您要将标准输出推送到文件,您希望对其进行完全缓冲以提高效率。

但是当您无法确定设备是非交互式的(即正常输出到终端)时,我在标准中找不到关于输出是行缓冲还是非缓冲的提及.

我问的原因是对我的答案的评论 here我应该在两个语句之间插入一个 fflush(stdout); :

printf ("Enter number> ");
// fflush (stdout); needed ?
if (fgets (buff, sizeof(buff), stdin) == NULL) { ... }

因为我没有用换行符终止printf。谁能解决这个问题吗?

最佳答案

C99 标准没有指定这三个标准流是无缓冲的还是行缓冲的:这取决于实现。我知道的所有 UNIX 实现都有行缓冲的 stdin。在 Linux 上,stdout 是行缓冲的,而 stderr 是无缓冲的。

据我所知,POSIX 并没有施加额外的限制。 POSIX 的 fflush页面在“示例”部分中确实注明:

[...] The fflush() function is used because standard output is usually buffered and the prompt may not immediately be printed on the output or terminal.

所以您添加 fflush(stdout); 的注释是正确的。

<小时/>

另一种方法是使 stdout 无缓冲:

setbuf(stdout, NULL);
/* or */
setvbuf(stdout, NULL, _IONBF, 0);

但正如 R. 所指出的,您只能执行一次此操作,并且必须在写入 stdout 或对其执行任何其他操作之前。 (C99 7.19.5.5 2)

<小时/>

我刚刚读了一篇recent threadcomp.lang.c 上也有同样的事情。备注之一:

Unix convention is that stdin and stdout are line-buffered when associated with a terminal, and fully-buffered (aka block-buffered) otherwise. stderr is always unbuffered.

关于stdout - 默认情况下,stdout 行是缓冲的、无缓冲的还是不确定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3723795/

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