To copy the data from one file store it into another file is called as merging of two files.
These are the steps that we need to follow while merging two files.
1. Open the files1 and file2 in the read mode
2. Read the character by character and store it in another file.
Let us see the below example code and run it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <iostream> using namespace std; int main (int nNumberofArgs, char* pszArgs[]) { FILE *pcFile1, *pcFile2, *pcFile; char ch, pszFile1[20], pszFile2[20], pszFile3[20]; cout << "Enter name of first file"<<"\n"; gets(pszFile1); cout << "Enter name of second file"<<"\n"; gets(pszFile2); cout << "Enter name of file which will store contents of two files"<<"\n"; gets(pszFile3); pcFile1 = fopen(pszFile1,"r"); pcFile2 = fopen(pszFile2,"r"); if( pcFile1 == NULL || pcFile2 == NULL ) { perror("Error "); cout << "Press any key to exit..." << "\n"; getchar (); exit(EXIT_FAILURE); } pcFile = fopen(pszFile3, "w"); if( pcFile == NULL ) { perror("Error "); cout << "Press any key to exit..." << "\n"; exit(EXIT_FAILURE); } while( ( ch = fgetc(pcFile1) ) != EOF ) fputc(ch,pcFile); while( ( ch = fgetc(pcFile2) ) != EOF ) fputc(ch,pcFile); cout <<"Two files were merged into %s file successfully." << pszFile3; fclose (pcFile1); fclose (pcFile2); fclose (pcFile); return 0; } |