Skip to content
Advertisement

Copy a file from one directory to another in C++

I am writing a C++ program to copy one file from one directory to another. I don’t want to use C++ 17 features. I have already implemented this in the following code.

#include <iostream>
#include <exception>
#include <filesystem>

using std:: cout;
using std:: cin;
using std:: endl;

int main(int argc, char* argv[])
{
    if(argc != 3) {
        cout << "Usage: ./copyFile.out path_to_the_file destination_path";
        return 1;
    }
    std:: string source = argv[1];
    std:: string destination = argv[2];
    std:: filesystem:: path sourceFile = source;
    std:: filesystem:: path targetParent = destination;
    auto target = targetParent / sourceFile.filename();

    try
    {
        std:: filesystem:: create_directories(targetParent); // Recursively create the target directory path if it does not exist.
        std:: filesystem:: copy_file(sourceFile, target, std ::filesystem ::copy_options::overwrite_existing);
    }
    catch (std::exception& e) //If any filesystem error
    {
        std::cout << e.what();
    }
    return EXIT_SUCCESS;
}

I am on Linux and I want to use the OS cp command to do this. I have written this code.

#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[]) {

    std:: string source, destination;

    if(argc != 3) {
        cout << "Usage: ./copyFile.out path_to_the_file destination_path";
        return 1;
    }

    source = argv[1];
    destination = argv[2];

    system("cp source destination");
}

The error is: cp: source: No such file or directory, How do I do this using system()?

Advertisement

Answer

Change this:

system("cp source destination");

To this:

std::string cmd = std::string("cp '") + source + "' '" + destination + "'";
system(cmd.c_str());

And BTW, you should either return from inside the if(argc != 3) statement, or do the rest of the code inside an else statement.

Lastly, function int main(int argc, char *argv[]) requires that you return an int value.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement