Hello, I am a newbie in c++. I have done file copy program which copies two file and makes new file to write. But this has limitations, it doesn't consider whitespace while writing. I want to modify it so that input is read as vector, and it is written as vector for output as well. Here is my program.
int main()
{
ifstream ifile1, ifile2;
ofstream ofile;
char ch;
string fname1, fname2, fname3;
cout<<"\n\n Merge two files and write it in a new file :\n";
cout<<"-------------------------------------------------\n";
cout<<" Input the 1st file name : ";
cin>>fname1;
cout<<" Input the 2nd file name : ";
cin>>fname2;
cout<<" Input the new file name where to merge the above two files : ";
cin>> fname3;
ifile1.open(fname1);
ifile2.open(fname2);
if (!ifile1 || !ifile2 )
{
perror("fopen()");
cout<<" File does not exist or error in opening...!!\n";
exit(EXIT_FAILURE);
}
ofile.open(fname3);
if (!ofile)
{
cout<<" File does not exist or error in opening...!!\n";
exit(EXIT_FAILURE);
}
while (ifile1.eof()==0)
{
ifile1>>ch;
ofile << ch;
}
while (ifile2.eof()==0)
{
ifile2 >> ch;
ofile << ch;
}
cout<<" The two files merged into %s file successfully..!!\n\n"<<fname3;
ifile1.close();
ifile2.close();
ofile.close();
return 0;
}
Second thing, I want to do it with a function (function for reading, and function for writing)
PPS. It's sometimes more convenient to read the file into a std::string rather than a std::vector - depending upon what, if any, manipulation of the container is required.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream ifs("input.txt");
if (!ifs)
return (std::cout << "Cannot open file\n"), 1;
const std::string fdata((std::istream_iterator<char>(ifs >> std::noskipws)), std::istream_iterator<char>());
for (constauto& f : fdata)
std::cout << f;
std::ofstream ofs("output.txt");
ofs.write(fdata.data(), fdata.size());
}