C Language | Advanced Features | Standard I/O - fprintf(), fscanf()

Command output and keyboard input are represented by special FILE streams.

Basic Input and Output

printf() writes to standard output, and scanf() reads from standard input. Standard error is a separate stream intended for error messages. Users can redirect these streams without modifying the program.

The streams are provided by stdio.h.

FILE *stdin;
FILE *stdout;
FILE *stderr;

They can be used with file-oriented functions.

#include <stdio.h>

int main() {
  char chError[0xFF];
  fputs("Enter an error message. >", stdout);
  fgets(chError, 0xFF, stdin);
  fputs(chError, stderr);
  return 0;
}

Use fprintf() and fscanf() for formatted stream I/O.

int fprintf(FILE *stream, const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);

Except for the stream argument, they work like printf() and scanf().

#include <stdio.h>

int main() {
  char chSelect;
  fprintf(stdout, "Select output. o/e>");
  fscanf(stdin, "%c", &chSelect);

  switch (chSelect) {
  case 'e':
  case 'E':
    fprintf(stderr, "Kitty on your lap\n");
    break;
  case 'o':
  case 'O':
    fprintf(stdout, "Kitty on your lap\n");
    break;
  }
  return 0;
}

Passing a file stream instead of stdin, stdout, or stderr applies the same formatted I/O operations to a file.