Monday 5 August 2013

Merging 2 sorted files into another file (sorted)

If file1.txt contains  6 7 8 9 10  12 48  and  file2.txt contains 1  3 5 11

Outfile.txt would contain 1 3 5 6 7 8 9 10 11 12 48

#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
int main()
{ifstream f1("File1.txt");
ifstream f2("File2.txt");
ofstream outfile("Outputfile.txt");
if(f1.fail()||f2.fail()||outfile.fail())
{
    cout<<"File accesing failed";
    exit(1);
}
int c,x;
f1>>c;
f2>>x;
while(!f1.eof() || !f2.eof())
{
    if(f1.eof())
    { while(!f2.eof())
       { cout<<x<<" ";
       outfile<<x<<" ";
       f2>>x;
       }
    }
   else if(f2.eof())
    {
     while(!f1.eof())
       { cout<<c<<" ";
        outfile<<c<<" ";
       f1>>c;
       }
    }

   else if(c > x)
     {  cout<<x<<" ";
      outfile<<x<<" ";
      f2>>x;
     }
     else
     { cout<<c<<" ";
      outfile<<c<<" ";
     f1>>c;
     }

}
f1.close();
f2.close();
outfile.close();


return 0;

}

No comments:

Post a Comment