How To: Use fprintf in C

The fprintf() function is probably my favourite (yes I am in Canada, and this is how it is spelled) stream output function. The beauty of fprintf over printf is it allows you to specify what stream you would like to output to, whereas printf will always output to standard out. In fact I use fprintf as part of my debugging macros in C, that I mentioned in an earlier article. The other interesting thing about the fprintf function is its ability to format output in a human readable form (in some cases).

The basic function is:

int fprintf(FILE *stream, const char *format, ..

Where the … is the sequential order of variables matching the format characters used.

Output to Standard Out Using fprintf

Here is a quick example of fprintf printing to standard out, as well as various formatting options available to it.

#include <stdio.h>
 
int main(int argc, char **argv)
{
  fprintf(stdout,"Day: %s,#1: %d,#2: %05d,hex: %x,float: %5.2f,unsigned value: %u.\n",
              "Tuesday", 1337, 89, 255, 3.141592654, 1250);
 
  return 0;
}

erik@debian:/fprintf_example$ ./fprintf_example
Day: Tuesday, #1: 1337, #2: 00089, hex: ff, float: 3.14, unsigned value: 1250.

Now that’s not so bad, is it. So as you can see,

  • %s is printing out my string of “Tuesday”.
  • %d is used for decimal values, in this case 1337.
  • %05d is also decimal, but the 05 states 5 (five) decimal places.
  • %x is used to display a value in hexadecimal, in our case 255 which is FF in hex.
  • %5.2f or f for floating point, in this case two decimal places.
  • %u is used for an unsigned value.

This example also shows us using stdout for standard out as the first argument to fprintf. This can be replaced by, stdout, stderr or a file handle on a previously opened file.

Output to a File Using fprintf

The first argument of fprintf takes a stream pointer, so we can actually pass in a file handle that has been opened previously. Refer to my earlier File Input / Output in C – Examples for some tips on doing so.

FILE *fp;
fp = fopen( "out_file.txt", "w" ); // Open file for writing
if(fp)
  fprintf(fp, "Hello %s\n", "reader");

Return Value of fprintf

The return value of fprintf is the number (as an integer) of characters that was written to whichever stream you are using, excluding the ‘\0′ or endline character.

For more formatting options refer to the manual page of fprintf here.