这是代码:
#include <stdio.h>
#include <unistd.h>
void main(){
char str1[18]= "moo\0 cuek\n";
printf("lel: %s",str1);
write(STDOUT_FILENO,str1,18);
write(STDOUT_FILENO,"meow ",19);
}
,输出为:
moo cuek
meow moo cuek
lel:moo
此外,为什么先打印meow
,然后再打印moo cuek
(第二行)
P.S。当我将\n
放在printf中时,例如:
printf("lel: %s \n",str1);
我得到:
lel:moo
moo cuek
meow moo cuek
为什么?!
答案 0 :(得分:4)
这里
printf("lel: %s",str1);
printf()
在文件流上打印数据,该文件的数据流指向该数据流,默认为stdout
流和stdout
流是行缓冲的,即您需要通过调用{{1}来刷新缓冲区}或添加fflush(stdout)
字符。对于例如
\n
或
printf("lel: %s",str1);
fflush(stdout);
或者您可以通过调用printf("lel: %s\n",str1); /* newline char has another use apart from giving newline i.e clear the buffer */
来禁用缓冲。
在这里
setbuf()
write(STDOUT_FILENO,str1,18);
是未缓冲的IO,即不缓冲数据,因此会立即将数据写入write()
。
答案 1 :(得分:0)
我不知道细节,但是基本上写入控制台的大多数功能都是缓冲的。这意味着当您调用该函数时,不一定是在打印文本时。 看到: Why does printf not flush after the call unless a newline is in the format string?