Why does printf not work before infinite loop?

不想你离开。 提交于 2019-12-22 09:48:55

问题


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) { }
}

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

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

Why is this? Thank you!


回答1:


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.




回答2:


Because you don't have a new-line character at the end of your string. stdout is line-buffered by default, which means it won't flush to console until it encounters a new-line character ('\n'), or until you explicitly flush it with fflush().




回答3:


Because the stdout hasn't been flushed.

Call

fflush(stdout);

before your loop.




回答4:


Perhaps the output is not getting flushed. Try:

printf("%s> ", path);
fflush(stdout);



回答5:


Because the output is not flushed. Add

fflush(stdout); 

before the while loop will solve the problem.



来源:https://stackoverflow.com/questions/7508630/why-does-printf-not-work-before-infinite-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!