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

(Romina) #1
Tip

If you don’t have a C: drive, change the C: in these examples to a different drive letter.
In fact, if you want to put your files in a specific folder but are not sure of the path,
right-click a file in that folder and select Properties from the menu. You should see the
directory path of the folder, which you can then use in your fopen() statement.

Click here to view code image


#include <stdio.h>
FILE *fptr; // Defines a file pointer
main()
{
fptr = fopen("c:\cprograms\cdata.txt", "w");
// rest of program would follow
fclose (fptr); // Always close files you've opened

For the rest of the program, you’ll access the cdata.txt file via the file pointer, not via the
filename. Using a file pointer variable is easier and less error prone than typing the filename and
complete pathname to the file every time you must access the file.


Warning

Close your filing cabinet drawers when you’re done with your files, or you’ll hit your
head! Close all open files when you’re finished with them, or you could lose some
data. fclose() is the opposite of fopen(). In its parentheses, fclose()
requires a file pointer of the file you want to close.

If the file pointer equals 0 , you know that an error happened. C returns a 0 from fopen() if an error
occurs when you open a file. For example, if you attempt to open a file on a disk drive that doesn’t
exist, fopen() returns an error.


The "w" (the second argument in the previous code’s fopen()) means write. The second argument
of fopen() must be one of the string mode values in Table 28.1.


TABLE 28.1 The Basic fopen() Mode Strings

Using Sequential Files


You’ll do only three things with a sequential file: create it, read it, and add to it (write to it). To write

Free download pdf