Why does “printf” not produce any output?

后端 未结 2 1177
借酒劲吻你
借酒劲吻你 2020-12-17 16:05

I am learning to program in C. Could you explain why nothing is printed here?

#include 

int main (void)
{
    char a[]="abcd         


        
相关标签:
2条回答
  • 2020-12-17 16:51

    Doing a fflush() could be expensive if you also have other streams other than stdout open for write, like say a file outputting to disk. Running fflush() will flush all streams not just stdout. It would be better to be more specific and pass the stream to flush. So for printf() which outputs to stdout you'd use fflush(stdout). A alternative if you're looking to output errors would be to use stderr as that's unbuffered with fprintf().

    Also you can use setvbuf to change an open streams buffer before writing to it. See man setvbuf

    0 讨论(0)
  • 2020-12-17 16:56

    On many systems printf is buffered, i.e. when you call printf the output is placed in a buffer instead of being printed immediately. The buffer will be flushed (aka the output printed) when you print a newline \n.

    On all systems, your program will print despite the missing \n as the buffer is flushed when your program ends.

    Typically you would still add the \n like:

    printf ("%s\n", a);
    

    An alternative way to get the output immediately is to call fflush to flush the buffer. From the man page:

    For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function.

    Source: http://man7.org/linux/man-pages/man3/fflush.3.html

    EDIT

    As pointed out by @Barmar and quoted by @Alter Mann it is required that the buffer is flushed when the program ends.

    Quote from @Alter Mann:

    If the main function returns to its original caller, or if the exit function is called, all open files are closed (hence all output streams are flushed) before program termination.

    See calling main() in main() in c

    0 讨论(0)
提交回复
热议问题