A D
A D

Reputation: 809

Why does printf not work before infinite loop?

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!

Upvotes: 6

Views: 5373

Answers (5)

John Yang
John Yang

Reputation: 1360

Because the output is not flushed. Add

fflush(stdout); 

before the while loop will solve the problem.

Upvotes: 1

David Z
David Z

Reputation: 131600

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.

Upvotes: 9

flight
flight

Reputation: 7272

Perhaps the output is not getting flushed. Try:

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

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190943

Because the stdout hasn't been flushed.

Call

fflush(stdout);

before your loop.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

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

Upvotes: 3

Related Questions