Answer to Question #199944 in C++ for kaushal

Question #199944

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.


1
Expert's answer
2021-05-28T10:31:30-0400

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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog