换行符还会刷新缓冲区吗? [英] Does new line character also flush the buffer?

查看:245
本文介绍了换行符还会刷新缓冲区吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,诸如 endl\n 之间的差异之类的问题已在SO上得到了多次回答.但是他们只提到endl能够将缓冲区刷新到stdout上,而\n不能.

I understand that questions like, difference between endl and \n have been answered many times on SO. But they only mention that endl is able to flush the buffer onto the stdout, while \n, does not.

因此,通过对缓冲区进行刷新,我了解到的是,给定的输入存储在缓冲区中,并且仅在遇到endl或某些显式的flush函数时才传递给stdout.如果是这样,我期望以下代码:

So, what I understand by buffer being flushed is that, the input given is stored in a buffer, and is passed onto the stdout only when it comes across endl, or some explict flush functions. If so, I expected that the following code :

#include <iostream>
#include <unistd.h>

int main(void)
{
    std::cout << "Hello\nworld";
    sleep(2);
    std::cout << std::endl;

    return 0;
}

要显示:

2秒后

Hello
World

但是实际输出是:

Hello

2秒后

World

为什么会这样?

也不应将\n也存储在缓冲区中,并且仅当遇到endl时,才将缓冲区刷新/显示在stdout上,但是据我观察,\n的行为与endl.

shouldn't \n also be stored in the buffer and only when endl is encountered buffer is to be flushed/displayed onto the stdout, but from what I observe \n is acting the same way as endl.

推荐答案

将注释转换为答案.

这取决于cout的去向.如果它到达终端(交互式设备"),则无法完全缓冲-通常是行缓冲的,这意味着字符在换行符打印后出现,或者从理论上讲可以不缓冲.如果要转到管道或文件或其他非交互式目标,则endl会强制将数据输出,即使该流已完全缓冲(通常也是如此).

It depends on where cout is going. If it goes to a terminal ('interactive device'), then it can't be fully buffered — it is usually line buffered, meaning that characters appear after a newline is printed, or could in theory be unbuffered. If it is going to a pipe or file or other non-interactive destination, the endl forces the data out even if the stream is fully buffered, as it usually will be.

我还想知道我是否既未提供换行符也未提供endl,一旦到达程序末尾,输出将显示在stdout上,我知道它可以用于终端,但是否适用所有类型的stdout?

I also wanted to know if I provided neither new line character nor endl, will the output be displayed on the stdout once it reaches the end of the program, I know it does for terminal, but is it applicable to all types of stdout?

是的,当文件流在程序的(正常)端关闭时,将刷新待处理的输出.当缓冲区已满时,也会刷新它.如果程序中止,通常不会刷新待处理的输出.

Yes, when the file stream is closed at the (normal) end of the program, pending output will be flushed. It'll also be flushed when the buffer is full. If the program aborts, pending output usually won't be flushed.

这篇关于换行符还会刷新缓冲区吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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