FILE PROCESSING IN C
Data Hierarchy:
a. Characters – letters, digits and special characters
b. Fields – group of characters that has meaning e.g. person’s name
c. Records – a group of related fields
d. Files – group of related records
e. Data base – group of related files
Record Key – a unique field in each record that is used to retrieve a specific
record from the file. Also known as the primary key.
Files and Streams
When a file is opened for use, a stream is associated with the file.
Streams are communication channels (interfaces) between files and programs.
Standard input stream – allows a program to read data from the keyboard
Standard output stream – allows program to write data to a screen
PROCESSING FILES
Open a file:
To open a file and associate it with a stream, use fopen().The general format of the
function used for opening a file is:
FILE *cfptr; /* declares the variable cfptr as a pointer to the file */
cfptr = fopen(“filename”,”mode”); /* filename is the name of the file and
mode indicates how the file is to be opened */
Example: cfptr = fopen(“[Link]”, “w”) /* opens file students for
writing */
1
Closing a file:
The input output library supports the function to close a file; it is in the following
format.
fclose(file_pointer);
A file must be closed as soon as all operations on it have been completed. This
would close the file associated with the file pointer.
Example: fclose(cfptr);
Mode Meaning
r Open a text file for reading
w Create a text file for writing
a Append to a text file
r+ Open an existing text file for update (i.e. read or write)
w+ Create a text file for update. If the file already exist discard its
contents
a+ Append: open or create a text file for update. Writing is done at
the end