开发者

Why does printf not work before infinite loop?

开发者 https://www.devze.com 2023-04-06 09:01 出处:网络
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 infi

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> ", 开发者_JAVA百科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!


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.


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().


Perhaps the output is not getting flushed. Try:

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


Because the stdout hasn't been flushed.

Call

fflush(stdout);

before your loop.


Because the output is not flushed. Add

fflush(stdout); 

before the while loop will solve the problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号