开发者

Strange behaviour with fputs and a loop

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.


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);


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


fflush(stdout);


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜