当没有任何新行印在这个code缓冲区为什么脸红? [英] Why in this code the buffer is flushed when there isn't any newline printed?

查看:147
本文介绍了当没有任何新行印在这个code缓冲区为什么脸红?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <limits.h>
#include <windows.h>

void p(int n) {

    if (n == 0) return;

    p(n/10);

    if (n%10 < 5) {printf("%d",n%10); Sleep(1000);}

}

int main()
{
    printf("%d\n",INT_MAX-1);

    p(INT_MAX - 1);

    return 0;
}

它应该在一次打印都因为流缓冲,但它单独打印数字。我使用Windows下的gcc。

It should print everything at once because the stream is buffered but it prints the digits separately. I am using gcc under windows.

推荐答案

在C语言中有三种可能的缓冲国流:

In C there are three possible buffering states for streams:


  • _IONBF - 无缓冲;字符都应该尽快出现

  • _IOLBF - 行缓冲;字符应该出现一个新行后

  • _IOFBF - 全缓冲;人物不应该出现,直到流刷新

  • _IONBF - unbuffered; characters should appear ASAP
  • _IOLBF - line buffered; characters should appear after a newline
  • _IOFBF - fully buffered; characters should not appear until stream flushed

关于标准输出的初始状态,C11 7.21.3 / 7不得不说:

Regarding the initial state of stdout, C11 7.21.3/7 has to say:

由于刚打开,标准错误流不会完全缓冲;标准输入和标准输出流是完全缓冲当且仅当可确定该流不提及交互设备

As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

由于流的的你的情况交互设备,它们的不得的完全缓冲。因此,标准输出既可以行缓冲或无缓冲。我没有看到任何其他文本进一步缩小下来。

Since the stream is an interactive device in your case, they must not be fully buffered. Therefore, stdout may either be line buffered or unbuffered. I don't see any other text narrowing this down further.

显然,你的系统上,它缓冲模式开出。

Apparently on your system, it starts out in unbuffered mode.

您可以设置行缓冲带:

setvbuf(stdout, NULL, _IOLBF, 1024);

(我不完全相信你应该把最后的说法是什么,但我认为,这意味着它应该使用1024字节的缓冲区为行;如果这个限制被击中冲洗)。

(I'm not exactly sure what you're supposed to put for the last argument but I think this means that it should use a 1024-byte buffer for the line; flushing if that limit is hit).

然而,当我尝试这样做对的MinGW-W64 4.9.2,行缓冲出现的行为一样全缓冲。

However when I tried this on MinGW-w64 4.9.2, the line-buffering appeared to behave the same as fully-buffered.

我推测的理由是因为这个实现重定向​​功能的MSVC运行时库尽可能多的,也许是MSVC运行时不支持线缓冲。这可以解释为什么海合会决定将默认为无缓冲,因为这是比全缓冲互动节目更好。

I'd speculate that the reason is because this implementation redirects functionality to the MSVC runtime library as much as possible, and perhaps the MSVC runtime doesn't support line-buffering. Which would explain why gcc decides to default to unbuffered, as that is better for interactive programs than fully-buffered.

这篇关于当没有任何新行印在这个code缓冲区为什么脸红?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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