C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

29. Saving Random Files to Your Computer


In This Chapter


  • Opening random files

  • Moving around in a file


This chapter shows you how to skip around in a file, reading and writing data as you go. The
preceding chapter introduced methods you can use to write, read, or append data to a file. The
problem is, when you open a sequential file for reading, you can only read it.


Sometimes you might want to read a customer structure from disk and change the customer’s balance.
You certainly wouldn’t want to have to create a new file just so you could write that one change.
Instead, you would want to read the customer information into a variable, change it, and then write it
back to disk exactly where it first resided. As Figure 29.1 shows, random files let you skip around in
the file, reading and writing at any point you access.


FIGURE 29.1 Random files let you read and write data in any order.

The physical layout of a file doesn’t define the type of file (whether random or sequential). You can
create a file sequentially and then read and change it randomly. To C, a file is just a stream of bytes,
and the way you access it isn’t linked to any format of the file.


Opening Random Files


To read or write a file randomly, you must open the file randomly. Table 29.1 lists the modes that
access random files. As you can see, the cornerstone of random-access files is the use of the plus sign
combined with the access modes you learned about in the previous chapter.

Free download pdf