Chapter 11
Programming Problems Using File
11.1 Sorting a File of Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
11.2 Counting the Occurrences of Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
11.3 Counting the Occurrences of a Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
11.4 How to Comment Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
11.1 Sorting a File of Integers
This program reads integers from a file, sorts them, and stores the sorted integers into
another file. We have already learned how to read integers from a file in Section 10.2.2.
Chapter 9 explains how to sort arrays. Here we put these two things together. This is the
first few steps of the program:
1. Check whether there are command-line arguments for the input and the output file
names.
2. Open the input file.
3. Read integers from the file and count the number of integers in the file.
4. Allocate memory to store the integers.
As illustrated in Fig. 10.1, a file is a stream. Every time something is read from the file,
the stream moves forward. After counting the number of integers, the stream has reached
its end. To fill the array, it is necessary to read the file from the beginning again. We can
do this in several ways. One way is to close the file and open it again. The preferred way is
to use fseek. It goes to a particular position in a file. This is how to go to the beginning of
a file: fseek(fptr, 0, SEEK SET).
Some people believe that calling rewind is the same as fseek(fptr, 0, SEEK SET).
This is not true. The returned value of fseek reports whether it succeeds or not, but
rewind does not report either success or failure.
The remaining steps are:
5. Use fseek to go to the beginning of the file.
6. Read the file again and fill the array.
7. Sort the array.
8. Close the input file.
9. Open the output file.
10. Write the sorted array to the output file.
11. Close the output file.
12. Free the memory for the array.
The order of some of these steps may be changed. For example, the program may free the
array memory before or after closing the output file (steps 11 and 12). The orders of steps
8 and 9 can also be exchanged. However, the order of some steps cannot be changed. For
example, step 9 (opening the output file) must precede step 10 (writing to the output file).
This can only be determined by thinking logically about the code. When writing complex
programs, it is important to write down the steps before writing the code. This saves a lot
153