The next letter is L.
The next letter is M.
The next letter is N.
The next letter is O.
The next letter is P.
The next letter is Q.
The next letter is R.
The next letter is S.
The next letter is T.
The next letter is U.
The next letter is V.
The next letter is W.
The next letter is X.
The next letter is Y.
The next letter is Z.
As you can see, the eighth position of the alphabetical file, the letter H, now contains an asterisk. The
rest of the file remains unchanged.
Note
If you ran this program a second time and changed a different letter (say, the 15th
position of the alphabet, the O), your file would print with asterisks instead of H and O
because the change to the H is now permanent in the letters.txt file. You could
run the program 26 times and replace every letter if you wanted.
The Absolute Minimum
The goal of this chapter was to explain how random-access files work. When you open
a file in random-access mode, you can read and write to that file in any order you need
to. The fseek() function is the built-in function that skips around the file from
position to position.
Being able to change the contents of a file is important when you want to update file
data. Often you will want to change a person’s address, change an inventory item’s
quantity, and so on without rewriting the entire file as you would have to if you used
sequential file processing. Key concepts from this chapter include:
- Use a plus sign in the fopen() mode string if you need to change data in a file.
- Remember that fseek() moves a file pointer all around a random file so that you
can read or write from the beginning, middle, or end. - Don’t forget to close a file when you are done with it.
- Don’t attempt to work with a file if the fopen() fails (by returning a zero).