How I can print to stderr in C?

wad picture wad · Aug 17, 2016 · Viewed 243.8k times · Source

In C, Printing to stdout is easy, with printf from stdio.h.

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

Answer

Fantastic Mr Fox picture Fantastic Mr Fox · Aug 17, 2016

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