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

(Romina) #1
TABLE 29.1 The Random-Access fopen() Modes

Note

As with sequential files, the access mode is a string that appears as the last argument of
fopen(). You close open random files with fclose(), just as you do with
sequential files.

All three modes let you read and write to the file. The access mode you choose depends on what you
want to do first to the file. If the file exists and you want to access the file randomly, use the r+
mode. If you want to create the file, use w+. (If the file already exists, C overwrites the existing
version.) If you want to add to the end of a file but optionally “back up” and read and write existing
data, use a+.


Here is a sample fopen() statement that opens a new file for writing and reading:


Click here to view code image


fptr = fopen("C:\\Users\DeanWork\\letters.txt", "w+");

As with sequential files, the fptr variable must be a file pointer variable. The double backslash is
needed if you specify a pathname. Remember that fopen() returns a zero if the open fails.


Tip

You can store the filename in a character array and use the character array name in
place of an actual string literal for the filename.

Moving Around in a File


Use the fseek() function to move around in a file. After you open a file, C initializes the file
pointer to point to the next place in the file you can read or write. fseek() moves the file pointer so
that you can read and write at places that would normally not be pointed at using sequential access.
Here is the format of


Click here to view code image


fseek():
fseek(filePtr, longVal, origin);

The filePtr is the file pointer used in the fopen() function that used a random-access mode. The
longVal is a longint variable or literal that can be either positive or negative. The longVal is
the number of bytes to skip forward or backward in the file. The origin is always one of the values
shown in Table 29.2. origin tells fseek() where to start seeking.

Free download pdf