There are two text files, whose names are given by two String variables , file1
ID: 3533498 • Letter: T
Question
There are two text files, whose names are given by two String variables , file1 and file2. These text files have the same number of lines. Write a sequence of statements that creates a new file whose name consists concatenating the names of the two text files (with a "-" in the middle) and whose contents of merging the lines of the two files. Thus, in the new file, the first line is the first line from the first file, the second line is the first line from the second file. The third line in the new file is the second line in the first file and the fourth line is the second line from the second file, and so on. When finished, make sure that the data written to the new file has been flushed from its buffer and that any system resources used during the course of running your code have been released.(Do not concern yourself with any possible exceptions here-- assume they are handled elsewhere.)Type your question here
Explanation / Answer
Silly way of doing it in C, wasn't sure what language you even wanted it in.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *inFile1, *inFile2, *mergeFile;
char file1[81], file2[81], file3[81], temp[81];
printf("Enter name of first file ");
gets(file1);
printf("Enter name of second file ");
gets(file2);
printf("Enter name of file which will store contents of two files ");
gets(file3);
inFile1 = fopen(file1,"r");
inFile2 = fopen(file2,"r");
if( inFile1 == NULL || inFile2 == NULL )
{
perror("Error ");
printf("Press any key to exit... ");
getch();
exit(EXIT_FAILURE);
}
mergeFile = fopen(file3,"w");
if( mergeFile == NULL )
{
perror("Error ");
printf("Press any key to exit... ");
exit(EXIT_FAILURE);
}
while(fscanf(inFile1, " %[^ ]s", &temp)!= EOF){
fgetc(inFile1); //gets rid of the remaining newline from above scanf
fprintf(mergeFile, "%s ", temp); //prints own newline so last line doesn't combine since there isn't a new line to copy
fgets(temp, 80, inFile2); //gets string from second file
fputs(temp, mergeFile); //puts it into new file
}
fclose(inFile1);
fclose(inFile2);
fclose(mergeFile);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.