作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我最近一直在阅读 APUE,这时出现了一个基本问题。我的代码如下所示
#include <apue.h>
#define BUFFSIZE 4096
int main()
{
int n;
char buf[BUFFSIZE];
while((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
{
printf("n is %d\n", n); //this line is added by me for testing
if(write(STDOUT_FILENO, buf, n) != n)
err_sys("write error"); //functions defined by the book to print error message
}
if(n < 0)
err_sys("read error");
exit(0);
}
编译后,当我运行程序时如下图所示
> $ ./mycat
123456[enter]
n is 7
123456
1234[enter]
n is 5
1234
看起来它按照我的代码结构工作。而且我不太明白'enter'的功能。每次我按下“enter”时,读取函数都会终止并将包括“enter”产生的“\n”在内的字符传递给写入函数。所以它进入循环并首先打印读取的字符数。
但是,下面的测试似乎违背了上面的代码结构。
> $ ./mycat > data
123456[enter]
1234[enter]
^D
> $ cat data
123456
1234
n is 7
n is 5
程序好像是先把所有的字符写入文件,然后打印'n'的值,但是按照我的理解,应该先打印如下
n is 7
123456
n is 5
1234
想了又想,就是想不通。你能帮帮我吗?
最佳答案
write()
未缓冲。 printf()
发送到 stdout
是缓冲的,但在某种程度上取决于输出的位置。
如果stdout
的输出进入控制台,它是行缓冲的,如果不是,它是完全缓冲的,在你的第二个例子中导致在程序结束时被刷新,而调用 write()
的输出马上出去。
来自 man stdio
:
[...] the standard input and output streams are fully buffered if and only if the streams do not refer to an interactive device.
Output streams that refer to terminal devices are always line buffered by default;
关于c - 关于 UNIX 系统中的无缓冲 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22425725/
我是一名优秀的程序员,十分优秀!