将换行符添加到 printf() 是否等同于刷新流? [英] Is adding the newline character to printf() equivalent to flushing the stream?

查看:33
本文介绍了将换行符添加到 printf() 是否等同于刷新流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序显示了在发生除以零"等错误时,缓冲 I/O 如何导致程序出现问题:

The following program shows how buffered I/O can cause problems in programs when errors like 'divide by zero' happen:

int main()
{
    int a = 1, b = 0, c;

    printf("Dividing...");
    c = a/b;

    printf("Answer is: %d\n", c);
    return 0;
}

输出为浮点异常(核心转储).

很公平.但令人惊讶的是,如果我将第一个 printf 更改为 printf("Dividing...\n");,则该文本实际上会在程序崩溃之前打印出来(我在 Linux 上运行 GCC,通过方式).

Fair enough. But surprisingly, if I changed the first printf to printf("Dividing...\n");, this text actually gets printed before the program crashes (I'm running GCC on Linux, by the way).

我是否可以得出添加换行符等同于刷新的结论?如果是这样,如果我所有的 printf() 字符串都以 \n 结尾,我实际上是在剥夺自己享受缓冲 I/O 的好处吗?

Am I to conclude that adding a newline is equivalent to flushing? And if so, if all my printf() strings end in \n, I'm actually depriving myself of the benefits of buffered I/O?

推荐答案

如果你的标准输出是去终端,是的,它等于刷新,因为 printf() 将使用基于行的缓冲.

If your standard output is going to a terminal, yes, it's equal to flushing, as printf() will use line-based buffering.

如果它被重定向到一个文件,那么没有.在这种情况下,printf() 使用更大的缓冲区(通常对应于文件系统块大小或其他大小)来优化 IO.

If it's redirected to a file, then no. In this case printf() uses much bigger buffers, usually corresponding to file system block sizes or whatever, to optimize IO.

这篇关于将换行符添加到 printf() 是否等同于刷新流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆