FILE Handling
FILE Handling
When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the
file using a few commands in C.
You can easily move your data from one computer to another without any changes.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors such
as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily edit
or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides better security than
text files.
File Operations
In C, you can perform four major operations on files, either text or binary:
3. Closing a file
When working with files, you need to declare a pointer of type file. This declaration is needed for
communication between the file and the program.
FILE *fptr;
Opening a file is performed using the fopen() function defined in the stdio.h header file.
ptr = fopen("fileopen","mode");
For example,
fopen("newprogram.txt","w");
fopen("oldprogram.bin","rb");
Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first
function creates a new file named newprogram.txt and opens it for writing as per the mode
'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
Now let's suppose the second binary file oldprogram.bin exists in the location E:\cprogram.
The second function opens the existing file for reading in binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the file.
Closing a File
The file (both text and binary) should be closed after reading/writing.
fclose(fptr);
Here, fptr is a file pointer associated with the file to be closed.
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that fprintf()
and fscanf() expects a pointer to the structure FILE.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
This program takes a number from the user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C drive of your
computer. When you open the file, you can see the integer you entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fscanf(fptr,"%d", &num);
return 0;
}
This program reads the integer present in the program.txt file and prints it onto the screen.
If you successfully created the file from Example 1, running this program will get you the integer you
entered.
Other functions like fgetchar(), fputc() etc. can be used in a similar way.
Example:
#include <stdio.h>
int main(){
char c;
f1 = fopen("xyz.txt", "w");
while((c=getc(file))!=EOF)
fputc(c,f1);
printf("%c", c);
fclose(file);
fclose(f1);
return 0;
This program is copying content of file abc.txt to file xyz.txt character by character and also is
printing same to terminal.
getc(filepointer) returns a character which is stored in variable c and that is written in the file xyz.txt
through pointer f1 function used here is fputc(c,f1).
Reading and writing to a binary file
Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively
in case of binary files.
To write into a binary file, you need to use the fwrite() function. The functions take four arguments:
Syntax:
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
In this program, we create a new file program.bin. We declare a structure threeNum with three
numbers - n1, n2 and n3, and define it in the main function as num. Now, inside the for loop, we
store the value into the file using fwrite(). The first parameter takes the address of num and the
second parameter takes the size of the structure threeNum. Since we're only inserting one instance
of num, the third parameter is 1. And, the last parameter *fptr points to the file we're storing the
data. Finally, we close the file.
Function fread() also take 4 arguments similar to the fwrite() function as above.
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
In this program, you read the same file program.bin and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into
the structure num.
fseek() is used to move file pointer associated with a given file to a specific position.
If you have many records inside a file and need to access a record at a specific position, you need to
loop through all the records before it to get the record.
This will waste a lot of memory and operation time. An easier way to get to the required data can be
achieved using fseek().
As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax of fseek()
Syntax:
returns:
position defines the point with respect to which the file pointer needs to be moved. It has three
values:
SEEK_END : It denotes end of the file.
SEEK_SET : It denotes starting of the file.
SEEK_CUR : It denotes file pointer’s current position.
Example 5: fseek()
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
C unions are used to save memory. To better understand an union, think of it as a chunk of
memory that is used to store variables of different types. When we want to assign a new value to
a field, then the existing data is replaced with new data. C unions allow data members which are
mutually exclusive to share the same memory. This is quite important when memory is valuable,
such as in embedded systems. Unions are mostly used in embedded programming where direct
access to the memory is needed.
The main difference between structure and a union is that Structs allocate enough space to store
all of the fields in the struct. The first one is stored at the beginning of the struct, the second is
stored after that, and so on. Unions only allocate enough space to store the largest field listed, and
all fields are stored at the same space .
Syntax for declaring a union is same as that of declaring a structure except the keyword struct.
union union_name {
datatype field_name;
datatype field_name;
// more variables
};
Size of the union is the the size of its largest field because sufficient number of bytes must
be reserved to store the largest sized field. To access the fields of a union, use dot(.)
operator i.e., the variable name followed by dot operator followed by field name.
Initializing unions:
The difference between structure and union when their initialization is given below.
#include <stdio.h>
struct test1 {
int x, y;
};
union test {
int x, y;
};
int main() {
union test t;
printf ("After fixing y value the coordinates of t will be %d %d\n\n", t.x, t.y);
return 0;
The fields of a union cannot be initialized all at once. For a structure variable the output is fine but
for the union variable the answer does not seem to be correct because union can hold single value
for a member at a time i.e., the data is over-written in the memory. Obviously the use case we have
chosen is not suited for union but only struct. This example is only to demonstrate the behavior of
union and structure.