a) Program to copy contents
of one file to another file, files are passed as command line arguments
copy file1.txt file2.txt
b) Program to copy the contents of first file
into second file, character by character in reverse order.
Program a)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
int main(int argc, char* argv[])
{
if(argc != 3)
{
std::cerr << "Error: the program requires two arguments\n";
return 1;
}
std::ifstream ifs(argv[1]);
if(!ifs)
{
std::cerr << "Open file for reading failed\n";
return 1;
}
std::ofstream ofs(argv[2]);
if(!ofs)
{
std::cerr << "Open file for writing failed\n";
return 1;
}
std::copy(std::istreambuf_iterator<char>(ifs)
,std::istreambuf_iterator<char>()
,std::ostreambuf_iterator<char>(ofs));
return 0;
}
Program b)
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <string>
int main(int argc, char* argv[])
{
if(argc != 3)
{
std::cerr << "Error: the program requires two arguments\n";
return 1;
}
std::ifstream ifs(argv[1]);
if(!ifs)
{
std::cerr << "Open file for reading failed\n";
return 1;
}
std::ostringstream ost;
std::copy(std::istreambuf_iterator<char>(ifs)
,std::istreambuf_iterator<char>()
,std::ostreambuf_iterator<char>(ost));
std::string buffer = ost.str();
std::reverse(buffer.begin(), buffer.end());
std::istringstream ist(buffer);
std::ofstream ofs(argv[2]);
if(!ofs)
{
std::cerr << "Open file for writing failed\n";
return 1;
}
std::copy(std::istreambuf_iterator<char>(ist)
,std::istreambuf_iterator<char>()
,std::ostreambuf_iterator<char>(ofs));
return 0;
}
Comments
Leave a comment