cprintfstderr

How can I print to standard error in C with 'printf'?


In C, printing to standard output (stdout) is easy, with printf from stdio.h.

However, how can I print to standard error (stderr)? We can use fprintf to achieve it apparently, but its syntax seems strange. Maybe we can use printf to print to standard error?


Solution

  • The syntax is almost the same as printf. With printf you give the string format and its contents ie:

    printf("my %s has %d chars\n", "string format", 30);
    

    With fprintf it is the same, except now you are also specifying the place to print to:

    FILE *myFile;
    ...
    fprintf(myFile, "my %s has %d chars\n", "string format", 30);
    

    Or in your case:

    fprintf(stderr, "my %s has %d chars\n", "string format", 30);