【问题标题】:Copy a file from one directory to another in C++在 C++ 中将文件从一个目录复制到另一个目录
【发布时间】: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


【解决方案1】:

这也可以使用snprintf来实现

char cmdbuf[BUFFER_SIZE];// use macro for defining buffer size
snprintf(cmdbuf, sizeof(cmdbuf), "cp %s %s ",argv[1],argv[2]);
system(cmdbuf);

【讨论】:

    【解决方案2】:

    改变这个:

    system("cp source destination");
    

    到这里:

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

    顺便说一句,您应该从if(argc != 3) 语句中返回,或者在else 语句中执行其余代码。

    最后,函数int main(int argc, char *argv[]) 要求您返回一个int 值。

    【讨论】:

    • 嗯...我想知道("cp " + source + " " + destination).c_str() 在传递给system 函数之前是否被释放,因为这里的实际字符串是一个临时对象...
    • @TedLyngmo:因为潜在的空间,对吧?我想我的回答可能有更大的问题,请参阅我上面的评论。
    • 无论如何,听从你的建议(以及我自己的建议)...
    • @TedLyngmo:不确定 Linux,但在 Windows 中我很确定你只能使用 ",所以我这样做是为了以防在 Linux 上也一样。
    • 我知道我只是在 system() 中传递了一个字符串“cp source destination”,你能解释一下 c_str() 是如何使它工作的吗?
    猜你喜欢
    • 2020-06-22
    • 2012-02-15
    • 2017-11-18
    • 2013-06-01
    • 2014-08-12
    • 2013-10-24
    • 2011-10-24
    • 1970-01-01
    相关资源
    最近更新 更多