tags:

views:

90

answers:

4

When running the following code I get no output but I cannot work out why.

# include <stdio.h>

int main()
{
    fputs("hello", stdout);

    while (1);

    return 0;
}

Without the while loop it works perfectly but as soon as I add it in I get no output. Surely it should output before starting the loop? Is it just on my system? Do I have to flush some sort of buffer or something?

Thanks in advance.

+5  A: 

You have to flush stdout. This happens automatically when you write a newline character. Change the fputs to:

fputs("hello\n", stdout);

Or to:

fputs("hello", stdout);
fflush(stdout);
Dietrich Epp
A: 

Why should it? The stdio functions doesn't know what's happening outside, and surely won't know an infinite loop is coming. The buffer will be flushed only when it is full or explicitly requested.

KennyTM
A: 

I guess asking the question helped me find the solution. Flushing is required with fflush(..)

http://www.thinkage.ca/english/gcos/expl/c/lib/fflush.html

Jonathan
A: 

fflush(stdout);

Andreas Brinck