Merging Two Files using C++
Is there a simple way of merging File1 and File2 into OutFile without the use of arrays, only using fstream?
File1:
111 Joe Smith
333 Steve Smith
555 Ron Smith
File2:
222 Don Smith
444 Randy Smith
OutFile:
111 Joe Smith
222 Randy Smith
333 Steve Smith
444 Randy Smith
555 Ron Smith
Re: Merging Two Files using C++
Why don't you want to use arrays? (I can't think of any other way)
Re: Merging Two Files using C++
Unfortunately to make my life more difficult I was told not to. This is the code I have so far:
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream File1;
ifstream File2;
ofstream outFile;
string File1_fName, File1_lName;
string File2_fName, File2_lName;
int File1_acctNum, File2_acctNum;
File1.open("file1", ios::in);
File2.open("file2", ios::in);
outFile.open("out.txt", ios::out);
File1 >> File1_acctNum >> File1_fName >> File1_lName;
File2 >> File2_acctNum >> File2_fName >> File2_lName;
while (!File1.eof() && !File2.eof())
{
if (File2_acctNum > File1_acctNum)
{
outFile << File1_acctNum << '\t' << File1_fName << '\t'
<< File1_lName << " *\n";
outFile << File2_acctNum << '\t' << File2_fName << '\t'
<< File2_lName << " *\n";
File1 >> File1_acctNum >> File1_fName >> File1_lName;
File2 >> File2_acctNum >> File2_fName >> File2_lName;
cout << File2_acctNum << "\t" << File2_fName << "\t" << File2_lName << endl;
}
else if (File1.eof())
{
while (!File2.eof())
{
outFile << File2_acctNum << '\t' << File2_fName << '\t'
<< File2_lName << '\n';
}
}
else if (File2.eof())
{
while(!File1.eof())
{
outFile << File1_acctNum << '\t' << File1_fName << '\t'
<< File1_lName << '\n';
}
}
}
return 0;
}
Re: Merging Two Files using C++
Absolutely it's possible. The algorithm is pretty simple. here's a psuedcode example.
Code:
// read a line from reach file (file a, file b)
storedA = a.readline();
storedB = b.readline();
// loop until one of the files is empty
while(!a.eof() && !b.eof())
{
// if a comes before b, write it, and read the next line from A.
// loop until this next line doesn't come before line B
while(storedA comes before storedB)
{
write(storedA);
storedA = a.readline();
}
// repeat the process for B < A.
while(storedB comes before storedA)
{
write(storedB);
storedB = b.readline();
}
}
// here check if either of the files has reached End Of File.
// if true, write the rest of the other file.
You probably need to check for EOF inside each of the inner while loops, but I left that out. Good luck!
Re: Merging Two Files using C++
Don't use eof() in loop conditions. Directly check the stream objects.