gpt4 book ai didi

c - 在遇到换行符时,printf是否总是刷新缓冲区吗?

转载 作者:行者123 更新时间:2023-12-02 10:29:41 24 4
gpt4 key购买 nike

我的机器正在运行ubuntu 10.10,并且我正在使用标准的gnu C库。我的印象是,如果在格式字符串中描述了换行符,则printf将刷新缓冲区,但是以下代码似乎反复逆转了这种趋势。有人可以弄清楚为什么不刷新缓冲区。

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>

int main()
{
int rc;
close(1);
close(2);
printf("HI 1\n");
fprintf(stderr, "ERROR\n");

open("newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0600);
printf("WHAT?\n");
fprintf(stderr, "I SAID ERROR\n");

rc = fork();

if (rc == 0)
{
printf("SAY AGAIN?\n");
fprintf(stderr, "ERROR ERROR\n");
}
else
{
wait(NULL);
}

printf("BYE\n");
fprintf(stderr, "HI 2\n");

return 0;
}

运行该程序后,newfile.txt的内容如下。
HI 1
WHAT?
SAY AGAIN?
BYE
HI 1
WHAT?
BYE

最佳答案

不,该标准说,如果可以确定输出设备为非交互式设备,则stdout最初将被完全缓冲。

这意味着,如果将stdout重定向到文件,它将不会在换行符上刷新。如果要尝试强制将其设置为行缓冲,请使用setbufsetvbuf

C99的相关部分7.19.3 Files, paragraph 7指出:

At program startup, 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.



只要记住 5.1.2.3/6部分:

What constitutes an interactive device is implementation-defined.

关于c - 在遇到换行符时,printf是否总是刷新缓冲区吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62776784/

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