This C Program merges lines alternatively from 2 files & print result.
Here is source code of the C Program to merge lines alternatively from 2 files & print result. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program that Merges Lines Alternatively from 2 Files & Print Result
*/
#include<stdio.h>
main()
{
char file1[10], file2[10];
puts("enter the name of file 1"); /*getting the names of file to be concatenated*/
scanf("%s", file1);
puts("enter the name of file 2");
scanf("%s", file2);
FILE *fptr1, *fptr2, *fptr3;
fptr1=fopen(file1, "r"); /*opening the files in read only mode*/
fptr2=fopen(file2, "r");
fptr3=fopen("merge2.txt", "w+"); /*opening a new file in write,update mode*/
char str1[200];
char ch1, ch2;
int n = 0, w = 0;
while (((ch1=fgetc(fptr1)) != EOF) && ((ch2 = fgetc(fptr2)) != EOF))
{
if (ch1 != EOF) /*getting lines in alternately from two files*/
{
ungetc(ch1, fptr1);
fgets(str1, 199, fptr1);
fputs(str1, fptr3);
if (str1[0] != 'n')
n++; /*counting no. of lines*/
}
if (ch2 != EOF)
{
ungetc(ch2, fptr2);
fgets(str1, 199, fptr2);
fputs(str1, fptr3);
if (str1[0] != 'n')
n++; /*counting no.of lines*/
}
}
rewind(fptr3);
while ((ch1 = fgetc(fptr3)) != EOF) /*countig no.of words*/
{
ungetc(ch1, fptr3);
fscanf(fptr3, "%s", str1);
if (str1[0] != ' ' || str1[0] != 'n')
w++;
}
fprintf(fptr3, "\n\n number of lines = %d n number of words is = %d\n", n, w - 1);
/*appendig comments in the concatenated file*/
fclose(fptr1);
fclose(fptr2);
fclose(fptr3);
}
$ cc pgm51.c $ a.out enter the name of file 1 c.txt enter the name of file 2 a.txt $ vi merge2.txt All participants will be provided with 1:1 Linux Systems for Lab work. If participants want, they can bring their own laptops with Linux in it. This enable them to do lot of quality assignments even Sanfoundry internship programs are great learning opportunities. Students with proven credentials only are enrolled for this program and the duration of these programs ranges from 2-6 months full t after the classes are over. If they have Windows, we install virtualization software and Ubuntu Linux virtual appliance on top of windows system. ime. Student must be passionate about Technology topics. As part of Sanfoundry's biggest open learning initiative, we are looking for interns (student or working professional) in following technolog number of lines = 4 number of words is = 114
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at other example programs on File Handling, go to File Handling. If you wish to look at programming examples on all topics, go to C Programming Examples.
Related Posts:
- Watch Advanced C Programming Videos
- Check Computer Science Books
- Check C Books
- Apply for C Internship
- Practice Computer Science MCQs