The difference between stdout and STDOUT_FILENO

前端 未结 1 1723
半阙折子戏
半阙折子戏 2020-11-30 19:58

I was wondering the difference between stdout and STDOUT_FILENO in Linux C.

After some searching work, I draw the following conclusion. Cou

相关标签:
1条回答
  • 2020-11-30 20:25

    stdout is a FILE* "constant" giving the standard outout stream. So obviously fprintf(stdout, "x=%d\n", x); has the same behavior as printf("x=%d\n", x);; you use stdout for <stdio.h> functions like fprintf, fputs etc..

    STDOUT_FILENO is an integer file descriptor (actually, the integer 1). You might use it for write syscall.

    The relation between the two is STDOUT_FILENO == fileno(stdout)

    (Except after you do weird things like fclose(stdout);, or perhaps some freopen after some fclose(stdin), which you should almost never do! See this, as commented by J.F.Sebastian)

    You usually prefer the FILE* things, because they are buffered (so usually perform well). Sometimes, you may want to call fflush to flush buffers.

    You could use file descriptor numbers for syscalls like write(2) (which is used by the stdio library), or poll(2). But using syscalls is clumpsy. It may give you very good efficiency (but that is hard to code), but very often the stdio library is good enough (and more portable).

    (Of course you should #include <stdio.h> for the stdio functions, and #include <unistd.h> -and some other headers- for the syscalls like write. And the stdio functions are implemented with syscalls, so fprintf may call write).

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