Basics of File Handling in C
So far the operations using C program are done on a prompt / terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are:
Creation of a new file (fopen with attributes as a or a+ or w or w++)
Opening an existing file (fopen)
Reading from file (fscanf or fgets)
Writing to a file (fprintf or fputs)
Moving to a specific location in a file (fseek, rewind)
Closing a file (fclose)
The text in the brackets denotes the functions used for performing those operations.
Opening or creating file
For opening a file, fopen function is used with the required access modes. Some of the commonly used file access modes are mentioned below.
File opening modes in C:
r Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
w Searches file. If the file exists, its contents are overwritten. If the file doesnt exist, a new file is created. Returns NULL, if unable to open file.
wb Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
a Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesnt exist, a new file is created. Returns NULL, if unable to open file.
ab Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be created.
r+ Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL.
w+ Searches file. If the file exists, its contents are overwritten. If the file doesnt exist a new file is created. Returns NULL, if unable to open file.
wb+ Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
a+ Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesnt exist, a new file is created. Returns NULL, if unable to open file.
ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created