Book
Collection
Click for Table of Contents
© 2025 by Rance D. Necaise
C Primer for Python Programmers
Copyright © 2025
Rance D. Necaise

6.7 Standard I/O

The standard I/O devices (keyboard and terminal) are treated like text files. There are actually predefined file variables associated with the keyboard and the terminal.

  • stdin
  • stdout
  • stderr

Standard Output

When you use the printf function to display text to the terminal,

  1.   printf("This is a sample message.\n");

internally, this function actually calls the fprintf function using the stdout file variable

  1.   fprintf(stdout, "This is a sample message.\n");

Standard Input

Likewise, when the scanf function is used,

  1.   scanf("%d", &idNum);

the fscanf function is called with the stdin file variable

  1.   fscanf(stdin, "%d", &idNum);

Thus, the printf and scanf functions are just shortcuts for the fprintf and fscanf functions, respectively.

Standard Error

C also defines a second standard output file variable stderr, which writes to the terminal in the same fashion as stdout.

  1.   fprintf(stderr, "Error: This is an error message.\n");

If we already have stdout, why do we need stderr? The stderr output file variable allows text to be written to the terminal even when standard output is redirected. Recall from earlier that you can redirect the output of a Linux command or program at the command-line prompt

  ./mypgm > output.txt

The intent here is to write the output of the program to the text file output.txt. But what if we need to print error messages or other information to the terminal that we do not want to be redirected to the output file? This is where the stderr file variable comes into play. When the output of a file is redirected, only the standard output is redirected, not standard error.

Thus, the stderr file variable is used to display error messages and other important information that should still be printed to the terminal when the user chooses to redirect the standard output. For example, the error message displayed earlier when there was an error opening a file, should be written to standard error

  1.   if(!infile) {
  2.     fprintf(stderr, "Error: The input file can not be opened.\n");
  3.     exit(1);     // The exit() function is defined in stdlib.h
  4.   }