Reputation: 53
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()?
Upvotes: 2
Views: 2316
Reputation: 31
This can also be achieved using snprintf
char cmdbuf[BUFFER_SIZE];// use macro for defining buffer size
snprintf(cmdbuf, sizeof(cmdbuf), "cp %s %s ",argv[1],argv[2]);
system(cmdbuf);
Upvotes: 1
Reputation: 6206
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.
Upvotes: 1