In this tutorial, you will learn about c programming files IO operations and functions associated with it.
So far we have used i/o functions like printf
and scanf
to write and read data. These are console oriented functions used when data is small.
So for handling large data, a new approach is introduced in c programming called file handling where data is stored on the local machine and can be operated without destroying any data.
A file simply is a collection of data stored in the form of a sequence of bytes in a machine.
Before jumping onto file handling functions we must know about the types of files used in c programming language.
Text files are humanly readable which is displayed in a sequence of characters that can be easily interpreted by humans as it presented in the textual form. Common editors like notepad and others can be used to interpret and edit them.
They can be stored in plain text (.txt) format or rich text format (.rtf).
In binary files data is displayed in some encoded format (using 0’s and 1’s) instead of plain characters. Typically they contain the sequence of bytes.
They are stored in .bin
format.
Thus C supports some functions to handle files and performs some operations. It includes:
For any file handling operations first, a pointer of FILE
type must be declared in C.
For example:
FILE *fp;
[adsense1]
As mentioned in above table fopen()
is a standard function used to create a new file or open an existing file from our local machine.
The general format for declaring and opening a file is:
FILE *ptr;
fp = fopen("filename","mode");
First, a pointer fp
of FILE
type is declared. In the second statement, fopen
function is used to open the file named filename
with a purpose which is defined by the mode.
The file is assigned to pointer variable fp
which is used as the communication link between the system and the program.
The purpose of opening a file is defined by mode. It can be any of the following:
For example:
FILE *fp;
fp = fopen("C://myfile.txt","r");
Here in this example, ‘myfile.txt’ will be opened in reading mode and if the file doesn’t exist in the specified location, it will return NULL.
NOTE: if the mode is writing mode then a new file will be created if the file doesn’t exist.
A file must be closed once it is opened and all operations are done because of various reasons like it will prevent any accidental misuse of the file. Moreover, sometimes the number of files that can be opened simultaneously is limited. So it is always best to close files once all operations are finished.
fclose()
is used for closing a file.
fclose(fp); // fp was the pointer to which our previously opened file was assigned