ابزار کاربر

ابزار سایت


c-system-programming:fprintf-dprintf

تابع ()fprintf و ()dprintf برای نوشتن در stdout و stderr

// man 3 printf
/* fprintf() write output to the given stdio(3) output stream */
int fprintf(FILE *restrict stream, const char *restrict format, ...);
 
/* dprintf() write output to the given file descriptor */
int dprintf(int fd, const char *restrict format, ...);
 
dprintf():
    Since glibc 2.10:
        _POSIX_C_SOURCE >= 200809L
    Before glibc 2.10:
        _GNU_SOURCE
/* output.c */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
 
int main(void)
{
   printf("A regular message on stdout\n");
 
   /* Using streams with fprintf() */
   fprintf(stdout, "Also a regular message on "
      "stdout\n");
   fprintf(stderr, "An error message on stderr\n");
 
   /* Using file descriptors with dprintf().
    * This requires _POSIX_C_SOURCE 200809L
    * (man 3 dprintf)*/
 
   /* /dev/stdout -> /proc/self/fd/1 */
   dprintf(1, "A regular message, printed to "
      "fd 1\n");
 
   /* /dev/stderr -> /proc/self/fd/2 */
   dprintf(2, "An error message, printed to "
      "fd 2\n");
 
   return 0;
}
$ make output
cc     output.c   -o output
$ ./output
A regular message on stdout
Also a regular message on stdout
An error message on stderr
A regular message, printed to fd 1
An error message, printed to fd 2
$ ./output  2> /dev/null
A regular message on stdout
Also a regular message on stdout
A regular message, printed to fd 1
$ ./output  > /dev/null
An error message on stderr
An error message, printed to fd 2
$ ./output  &> /dev/null
c-system-programming/fprintf-dprintf.txt · آخرین ویرایش: 2024/06/18 01:22 توسط pejman

به جز مواردی که ذکر می‌شود، مابقی محتویات ویکی تحت مجوز زیر می‌باشند: Public Domain
Public Domain Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki