why doesn't this c programme print the first printf statement?

前端 未结 3 1105
生来不讨喜
生来不讨喜 2020-12-15 12:39
#include
#include 
int main(){
      while(1)
      {

              fprintf(stdout,\"hello-out\");
              fprintf(stderr,\"hel         


        
相关标签:
3条回答
  • 2020-12-15 13:03

    It doesn't always print out the output to stdout because by design stdout is BUFFERED output, and stderr is unbuffered. In general, the for a buffered output stream, the stream is not dumped until the system is "free" to do so. So data can continue buffering for a long while, before it gets flushed. If you want to force the buffer to flush you can do so by hand using fflush

    #include<stdio.h>
    #include <unistd.h>
    int main(){
          while(1)
          {
    
                  fprintf(stdout,"hello-out");
                  fflush(stdout); /* force flush */
                  fprintf(stderr,"hello-err");
                  sleep(1);
          }
          return 0;
    }
    

    Update: stdout is linebuffered when connected to a terminal, and simply buffered otherwise (e.g. a redirect or a pipe)

    0 讨论(0)
  • 2020-12-15 13:09

    You forgot newlines (noted \n) in your strings. Or you need to call fflush(NULL); or at least fflush(stdout); before sleep(1);

    And fprintf(stdout, ...) is the same as printf(...)

    You need to output newlines or to call fflush because (at least on Linux) the stdout FILE buffer is line-buffered. This means that the C library is buffering data, and will really output it (using the write Linux system call) when the buffer is full enough, or when you flush it either with a new line, or by calling fflush. Buffering is needed because system calls are costly (calling write for every byte to be output is really too slow). Read also the man page of setbuf

    0 讨论(0)
  • 2020-12-15 13:10

    If you add a '\n' to your message it will (or should), ie. "hello-out\n".

    The reason being is that stdout is buffered in order to be more efficient, whereas stderr doesn't buffer it's output and is more appropriate for error messages and things that need to be printed immediately.

    stdout will usually be flushed when:

    • A newline (\n) is to be printed
    • You read in from stdin
    • fflush() is called on it

    EDIT: The other thing I wanted to add before my computer crashed...twice...was that you can also use setbuf(stdout, NULL); to disable buffering of stdout. I've done that before when I've had to use write() (Unix) and didn't want my output to be buffered.

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