fprintf function --outputs the formatted string to the output destination

The fprintf function can output a formatted character string by specifying the output destination. The printf function outputs to the standard output, but the fprintf function can specify the output destination. You can use it by reading the stdio.h header.

#include <stdio.h>
int fprintf (FILE * fp, const char * format, ...);

Output to standard output

Let's use the fprintf function to output to standard output. Do the same as the printf function. stdout is a pointer to a FILE structure that means a standard output stream.

#include <stdio.h>

int main (void) {
  const char * message = "Hello";
  fprintf (stdout, "%s\n", message);
}

This is the output result.

Hello

Output to standard error output

Let's use the fprintf function to output to standard error output. stderr is a pointer to the FILE structure, which means standard error stream.

#include <stdio.h>

int main (void) {
  const char * message = "Hello";
  fprintf (stderr, "%s\n", message);
}

This is the output result. It is output to the error output.

Hello

Output to file

Let's print it to a file using the fprintf function. Let's open the file with the fopen function and write to the file. The opened file is closed with the fclose function.

#include <stdio.h>
#include <stdlib.h>

int main (void) {
  
  // Open the file for writing
  const char * out_file = "output.txt";
  FILE * out_fp = fopen (out_file, "w");
  if (out_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", out_file);
    exit (1);
  }
  
  // Write to a file with the fprintf function
  const char * message = "Hello";
  fprintf (out_fp, "%s\n", message);
  
  // Close the file
  fclose (out_fp);
}

Let's open output.txt. The following contents are output.

Hello

Associated Information