为什么printf在无限循环之前不起作用? [英] Why does printf not work before infinite loop?

查看:227
本文介绍了为什么printf在无限循环之前不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个包含无限循环的小程序,以等待用户输入的信号。我想在开始无限循环之前打印出关于当前工作目录的消息。该消息可以自行运行,但是当我将无限循环放入代码时,消息不会打印出来(但终端会无限循环)。代码是:

I am trying to make a small program that includes an infinite loop to wait for signal input from the user. I wanted to print out a message about the current working directory before beginning the infinite loop. The message works on its own, but when I put the infinite loop into the code the message does not print out (but the terminal does loop infinitely). The code is:

#include <stdio.h>

int MAX_PATH_LENGTH = 100;

main () {
  char path[MAX_PATH_LENGTH];
  getcwd(path, MAX_PATH_LENGTH);
  printf("%s> ", path);
  while(1) { }
}

如果我拿出 while(1){} 我得到输出:

If I take out while(1) { } I get the output:

ad@ubuntu:~/Documents$ ./a.out
/home/ad/Documents>

这是为什么?谢谢!

推荐答案

当你打电话给 printf 时,输出没有'立即打印;相反,它会在幕后的某个地方进入缓冲区。为了实际让它显示在屏幕上,你必须调用 fflush 或类似的东西来刷新流。无论何时打印换行符*和程序终止时,都会自动完成此操作;这是第二种情况,当你删除无限循环时会导致字符串出现。但是在那里有循环,程序永远不会结束,所以输出永远不会刷新到屏幕上,你什么都看不到。

When you call printf, the output doesn't get printed immediately; instead, it goes into a buffer somewhere behind the scenes. In order to actually get it to show up on the screen, you have to call fflush or something equivalent to flush the stream. This is done automatically for you whenever you print a newline character* and when the program terminates; it's that second case that causes the string to show up when you remove the infinite loop. But with the loop there, the program never ends, so the output never gets flushed to the screen, and you don't see anything.

*正如我刚刚通过阅读注释中链接的问题所发现的那样,只有在程序打印到终端时才会发生刷新换行,而不一定是在打印到文件时。

*As I just discovered from reading the question itsmatt linked in a comment, the flush-on-newline only happens when the program is printing to a terminal, and not necessarily when it's printing to a file.

这篇关于为什么printf在无限循环之前不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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