C语言中I/O流的一些疑惑

来源:互联网 发布:中世纪2优化 战报 编辑:程序博客网 时间:2024/05/20 18:48

关于I/O流,初学会碰到一些很奇怪的现象。程序如下:

int main()
{
    while(1)
    {
        fprintf(stdout,"hello-out");
        fprintf(stderr,"hello-err");
        sleep(1);
    }
    return 0;
}

 

在终端下屏幕只是输出的只有hello-err,而不输出hello-out,非常让人疑惑

把程序稍微改一下:

int main(){while(1){fprintf(stdout,"hello-out");fflush(stdout);fprintf(stderr,"hello-err");sleep(1);}return 0;}
 

这次终端屏幕可以输出hello-out和hello-err,ffplush能立即把输出缓冲区的数据进行物理写入,能保证信息实时地打印出来,而
stderr是无缓冲的输出,保证错误提示和输出能够及时反馈给用户,供用户排除错误。在第一个程序中,hello-out写在缓冲区,一直
写到缓冲区满了屏幕才会输出hello-out,而且会输出很多个。
再把程序改一下:
int main(){while(1){fprintf(stdout,"hello-out/n");fprintf(stderr,"hello-err/n");sleep(1);}return 0;}

程序也可以输出hello-out和hello-err,这说明标准输出是行缓冲,遇到”/n”,就会进行I/O操作,这样也能及时地输出信息。
既然说到了fflush,那就再啰嗦一下,我们常见的调试策略是把一些printf函数散布于程序中,确定错误出现的具体位置。但是,这些
函数调用的输出结果被写到缓冲区中,并不立即显示在屏幕上。解决方法是priintf函数之后紧跟fflush函数
printf("somgthing is wrong?");fflusn(stdout);

参考资料:

1.《C和指针》  P299

2.http://hi.baidu.com/hp_roc/blog/item/47eedcef85e2b7dfb31cb19e.html

原创粉丝点击