How I can print to stderr in C? How I can print to stderr in C? c c

How I can print to stderr in C?


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);


Some examples of formatted output to stdout and stderr:

printf("%s", "Hello world\n");              // "Hello world" on stdout (using printf)fprintf(stdout, "%s", "Hello world\n");     // "Hello world" on stdout (using fprintf)fprintf(stderr, "%s", "Stack overflow!\n"); // Error message on stderr (using fprintf)


#include<stdio.h>int main ( ) {    printf( "hello " );    fprintf( stderr, "HELP!" );    printf( " world\n" );    return 0;}$ ./a.exeHELP!hello  world$ ./a.exe 2> tmp1hello  world$ ./a.exe 1> tmp1HELP!$
  1. stderr is usually unbuffered and stdout usually is. This can lead to odd looking output like this, which suggests code is executing in the wrong order. It isn't, it's just that the stdout buffer has yet to be flushed.Redirected or piped streams would of course not see this interleave as they would normally only see the output of stdout only or stderr only.

  2. Although initially both stdout and stderr come to the console, both are separate and can be individually redirected.