Introduction
In this post, I am going to write a c program to read two files simultaneously and display the contents on the screen. Simultaneously means we are reading two files at the same time. Before writing the program, let us see the two input files that we are going to read.
Also Read: Armstrong Number in C Programming
Input File 1
1
2
3
4
5
Input File2
India
America
Australia
New Zealand
Sri Lanka
As you can see, there are two different files and we need to read them simultaneously. So see the following output.
Expected Output

Also Read: C Program to Find All The Keywords In a File
I hope you have understood what we will have to do? Now see the following program.
C Program To Read Two Files Simultaneously and Display the Contents on the Screen
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
char line1[50],line2[50];
char *n1,*n2;
fp1=fopen("file1.txt","r");
fp2=fopen("file2.txt","r");
if((fp1==NULL)||(fp2==NULL))
{
printf("ERROR");
exit(1);
}
while(1)
{
n1=fgets(line1,sizeof(line1),fp1);
n2=fgets(line2,sizeof(line2),fp2);
if((n1==NULL)||(n2==NULL))
{
break;
}
printf("%s%s",line1,line2);
}
return 0;
}
Here, we are performing the following steps:
- Opening two files using fopen() function in reading mode i.e. file1.txt and file2.txt
- Checking whether these two files have been opened successfully or not.
- In the while loop, using two fgets() function, we are reading each line from both the files and storing those characters in the character array line1 and line2.
- Now, printing the values of the character arrays using printf() statement.
I hope, you have understood this program. If you have any difficulty regarding this program, then please feel free to contact me.
Thank you.