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

6.4 File Processing

Reading data from a text file that is then examined or manipulated in some way is known as file processing. When reading a collection of data or processing the contents of a file, we need a properly constructed input loop:

  1.    // priming read
  2.   while( condition ) {
  3.      //process data
  4.      //modification read
  5.   }

Remember, the condition in the input loop tests for or compares against the sentinel value, which indicates that we have finished reading data or reached the end of the input collection.

End of File

stdio.h

When reading and processing a file, the sentinel value is typically a test to determine if the end of file has been reached. In C, the feof function is used for this purpose

  1.    // priming read
  2.   while( !feof(infile) ) {
  3.      . . .
  4.     // modification read
  5.   }

The feof returns true if the end of file was reached during the last input operation (i.e. using either fscanf or fgetc). Note, that you must first try reading data from the input file before testing if the end of file was reached. Thus, the need for a priming read.

Processing Data

Consider a text file that contains a set of exam grades specified as integers stored one per line

  85
  90
  89
  75
  100
  98
  86

Suppose we want to compute the average exam grade for a collection of grades stored in a text file. This task can be accomplished using the following code segment:

  1.   int grade;
  2.   int sum = 0;
  3.   int count = 0;
  4.  
  5.   fscanf(infile, "%d", &grade);     // priming read
  6.   while(!feof(infile)) {            // test for end of file
  7.     sum = sum + grade;
  8.     count = count + 1;
  9.     fscanf(infile, "%d", &grade);   // modification read
  10.   }
  11.  
  12.   float avg = sum / float(count);
  13.   printf("Average exam grade = %0.2f\n", avg);