Merging Data Files

The times they are a-changin’.

This post seems to be older than 15 years—a long time on the internet. It might be outdated.

C++, while tedious, is probably one of my favorite classes. I’ve never actually taken a e first line of each file
//Write the higher valuprogramming class before now and I imagine I will be taking more. Anyways, another has gone by and thus another lab is due and you get to see what I’ve done! This week we worked on interacting with outside files. Just simple tasks, like opening, closing, reading, and writing. The program I had to create delt with taking two seperate files and merging them into one while activly sorting the numbers from lowest to highest. I could not merge the data and then sort it. Enjoy!

//Name: Andrew Ferguson
//Date: 2/27/2005
//Purpose: Merge two files while sorting the data

//Open two read files and one write file
//Read and compare the first line of each file
//Write the higher value to the screen and to the write file
//Read the next highest number from the file that containted the previous higher number and compare again
//Repeat until both read files are completly read

#include

#include
#include

int main(){
ifstream file_one, file_two;
ofstream fout;
double next_one, next_two;

file_one.open(“location1.dat”);
file_two.open(“location2.dat”);
fout.open(“output.dat”);

if(file_one.fail()){
cout << "File failed to open." << endl; exit(1); } if(file_two.fail()){ cout << "File failed to open." << endl; exit(1); } file_one >> next_one; //Prime the pump…so to speak
file_two >> next_two; //Prime the pump…so to speak

cout << "Merging Files..." << endl; while1 && (!file_two.eof())){ if(next_one <= next_two){ fout << next_one << endl; cout << next_one << endl; file_one >> next_one;
}
else{
fout << next_two << endl; cout << next_two << endl; file_two >> next_two;
}
while2 && (!file_two.eof())){
fout << next_two << endl; cout << next_two << endl; file_two >> next_two;
}
while3 && (!file_one.eof())){
fout << next_one << endl; cout << next_one << endl; file_one >> next_one;
}

}
file_one.close();
file_two.close();
fout.close();
cout << "...Complete!" << endl; } [/code]

Download the Windows Executable
File “Location1.dat”
File “Location2.dat”
The last two files are the files that are merged. You can download and use them or you can create your own files called location1.dat and location2.dat. If you create your own files, each file can contain as many floating points as you want with one per line. The files must be in the same directory as the program.

0
  1. !file_one.eof( 

  2. file_one.eof( 

  3. file_two.eof(