【发布时间】:2021-02-15 23:06:48
【问题描述】:
我正在编写一个 C++ 程序来将一个文件从一个目录复制到另一个目录。我不想使用 C++ 17 功能。我已经在下面的代码中实现了这一点。
#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;
}
我在 Linux 上,我想使用 OS cp 命令来执行此操作。我已经写了这段代码。
#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");
}
错误是:cp: source: No such file or directory,我该如何使用system()?
【问题讨论】:
-
你可以试试
std::string cmd = "cp " + source + " " + destination;然后system(cmd.c_str());`。 “source”不是源文件名! -
你到底为什么要从使用 C++17 功能到使用
system()来实现这一目标?
标签: c++ linux file directory copy