Tuesday, 20 January 2015

Merging of two files in C/C++ with examples

Merging of two files in C/Cpp with examples:

To copy the data from one file store it into the another file is called as merging of two files.

These are the steps that we need to follow while merging of two files.
1. Open the files1 and file2 in the read mode
2. Read the character by character and store it into another file.

Let us see the below example code and run it.


#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;
}



No comments: