Creation of a new file
Opening an existing file
Reading from a file
Writing to a file
Moving to a specific location in a file (seeking)
Closing a file
Opening a file:
Before we can read or write information from or to a file on a disk we must open the file.
To open the file we have called the function fopen( ). It opens a file in read mode which tells the C compiler that we would be reading the contents of the file.
fopen( ) performs three important tasks when you open the file in “reading” mode:
Firstly it searches on the disk the file to be opened.
Then it loads the file from the disk into a place in memory called buffer.
It sets up a character pointer that points to the first character of the buffer.
We have declared fp as
FILE *fp ;
The FILE structure has been defined in the header file “stdio.h”.
Therefore, it is necessary to #include this file.
Reading from a File:
Once the file has been opened for reading using fopen( ), as we have seen, the file’s contents are brought into buffer (partly or wholly) and a pointer is set up that points to the first character in the buffer.
To read the file’s contents from memory there exists a function called fgetc( ).
This has been used in our program as,
ch = fgetc ( fp );
Trouble in Opening a File:
There is a possibility that when we try to open a file using the function fopen( ), the file may not be opened. While opening the file in “r” mode, this may happen because the file being opened may not be present on the disk at all. And you obviously cannot read a file that doesn’t exist. Similarly, while opening the file for writing, fopen( ) may fail due to a number of reasons, like, disk space may be insufficient to open a new file, or the disk may be write protected or the disk is damaged and so on.
If the file opening fails due to any of the several reasons mentioned above, the fopen( ) function returns a value NULL.
Closing the File:
When we have finished reading from the file, we need to close it. This is done using the function fclose( ) through the statement, fclose ( fp ) ;
Once we close the file we can no longer read from it using getc( ) unless we reopen the file.On closing the file the buffer associated with the file is removed from memory.
When we close this file using fclose( ) three operations would be performed:
The characters in the buffer would be written to the file on the disk.
At the end of file a character with ASCII value 26 would get written.
The buffer would be eliminated from memory.