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

(Romina) #1

All disk files have names that conform to the same naming rules as filenames on your operating
system. Before you can use a disk file, whether to create, read, or change the data in the file, you must
open the file.


As with a filing cabinet, you can’t use a disk file without opening the file. Instead of pulling out a
drawer, your computer attaches something called a file pointer to the file and makes sure that the disk
is properly set up to hold the file you specify.


Opening a File


To open a file, you must use the fopen() function, whose description is included along with
printf()’s in stdio.h. Before seeing fopen(), you have to understand the concept of a file
pointer.


Note

The concept of a file pointer is easy to understand. A regular pointer holds the address
of data in a variable. A file pointer holds the disk location of the disk file you’re
working with.

You must specify a special statement to define a file pointer. As with any variable, you can name file
pointers anything you want. Suppose you want to open an employee file. Before the fopen(), you
must define a file pointer variable. If you called the file pointer fptr, here is how you would define
a file pointer:


Click here to view code image


FILE * fptr; /* Defines a file pointer named fptr */

Warning

Most C programmers define their file pointers before main(). This makes the file
pointer global, which is a fancy term meaning that the entire program can use the file.
(Most other kinds of variables are local, not global.) Because part of the file pointer
statement is in upper case, FILE is defined someplace with #define. FILE is
defined in stdio.h, which is the primary reason you should include the stdio.h
header file when your program uses the disk for data.

After you define a file pointer, you can connect that pointer to a file with fopen(). After you
specify fopen(), you can use the file throughout the rest of the program. Here is the way to open a
file named C:\cprograms\cdata.txt.

Free download pdf