linux下printf中"\n"刷新缓冲区的疑问(待解决--评论中的问题)

时间:2022-11-19 04:43:32
  #include <stdio.h>
#include <unistd.h>

int main(void)
{
printf("hello world");
close(STDOUT_FILENO);
return 0;
}
//什么都不输出
  #include <stdio.h>
#include <unistd.h>

int main(void)
{
printf("hello world\n");
close(STDOUT_FILENO);
return 0;
}
//hello world

通过上面的两个程序已经证明在linux下,“\n”确实对缓冲区有强制刷新的作用

  #include <sys/stat.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(void)
{
int fd;
close(STDOUT_FILENO);
fd = open("hello", O_CREAT|O_RDWR, 0644);
if(fd < 0){
perror("open");
exit(0);
}
printf("Nice to meet you!\n");
//fflush(stdout);
close(fd);
return 0;
}

但是第三段代码,当没有fflush函数强制刷新的时候,hello文件里面没有“Nice to meet you!”,在加上fflush函数之后,hello文件中就有“Nice to meet you!”了。
但是我已经在”Nice to meet you!\n”后面加上换行符,不是应该刷新文件缓冲区,使得”Nice to meet you!\n”写到hello文件当中去么?但是实际并没有,这是为什么 ,求解惑

  • 有网友说是因为控制台文件和常规文件的区别,那是不是可以这么认为,在C标准中,控制台有单独的缓存空间,有单独的运行规则,比如遇到\n就执行刷新操作,而常规文件中的缓存空间是没有这个设定的,有待进一步确定。

原因:只有stdout的缓冲区是通过‘\n’进行行刷新的,但是我开始的时候就把stdout就关闭了,就会像普通文件一样像文件中写,所以‘\n’是不会行刷新的,所以要使用fflush(stdout)。

stderr无缓冲,不用经过fflush或exit,就直接打印出来
stdout行缓冲 遇到\n刷新缓冲区