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

6.6 Processing Characters

Sometimes, you may want to read the text from the file as characters instead of numerical data. The fscanf function, however, as indicated in the previous section, skips over white space characters when reading individual characters from the file. If you need to read all characters, including white space characters, then you must use the fgetc function instead of the fscanf function. The fgetc function takes the file variable as an argument and returns the next character in the file without skipping over any other characters

  1.   int ch;
  2.   ch = fgetc(infile);

This function is typically used within a loop to read multiple characters from a text file. In the following program, we read the individual characters from the text file and simply display them to the terminal.

Listing
  1. /* showfile.cc
  2.  *
  3.  * Reads the contents of a text file and prints the contents to the terminal.
  4.  */
  5.  
  6. #include <stdio.h>
  7.  
  8. int main()
  9. {
  10.   FILE *infile;
  11.  
  12.    // Open the file and verify it was opened.
  13.   infile = fopen("document.txt", "r");
  14.   if(!infile) {
  15.     printf("Error: the input file could not be opened.\n");
  16.     exit(1);
  17.   }
  18.  
  19.    // Read the entire contents and print it to the terminal.
  20.   int ch;
  21.  
  22.   ch = fgetc(infile);           // priming read
  23.   while(!feof(infile)) {        // test for end of file
  24.     printf("%c", ch);
  25.     ch = fgetc(infile);         // modification read
  26.   }
  27.  
  28.    // Close the file
  29.   fclose(infile);
  30. }
Program: showfile.cc