// copy from 2 files to 1 file
// Approach 3: fin connect to 2 files, fout connect to 1 file
#include<iostream>
#include<fstream>
#include<string>
int main()
{
using namespace std;
const char* filename[3] = { "file1.txt","file2.txt","file3.txt" };// store file names
fstream finout[3];// every one can handle both input and ouput stream
// if can't open one of the files,not necessary to move on
for (int i = 0; i < 3; i++)
{
if (i == 2)
finout[i].open(filename[i], ios_base::in | ios_base::out|ios_base::app);// avoid file3 being covered
else
finout[i].open(filename[i]);
if (!finout[i].is_open())
{
cerr << "Failed to open file: " << filename[i] << endl;
exit(EXIT_FAILURE);
}
}
// copy to
while (!finout[0].eof() || !finout[1].eof())// after each getline(),input pointer steps forward
{
if (!finout[0].eof() && !finout[1].eof())// both file1 and file2 not reach eof
{
string str1, str2;// temp value
getline(finout[0], str1);
getline(finout[1], str2);
finout[2] << str1 + " " + str2 + '\n';
}
if (!finout[0].eof() && finout[1].eof())// only file1 not reach eof
{
string str1;
getline(finout[0], str1);
finout[2] << str1 + '\n';
}
if (finout[0].eof() && !finout[1].eof())// only file2 not reach eof
{
string str2;
getline(finout[1], str2);
finout[2] << str2 + '\n';
}
}
// disconnect
for (int i = 0; i < 3; i++)
finout[i].close();
cout << "Copy completed. Bye!";
cin.get();
return 0;
}
/*
Approach 1: fin connect to 2 files, fout connect to 1 file. fin need to frequently
connect and disconnect,negative
Approach 2: finout connect to 3, will frequently connect and disconnect, negative
Approach 3: fin1 connect to file1, fin2 connect to file2, fout connect to file3
can also use command line int main(int argc,char* argv[n])
*/
C++ Premier Plus 6th edition - Programming excercise - Chapter17 - 4
最新推荐文章于 2019-03-15 15:23:32 发布