如何将文件从文件夹复制到另一个文件夹

use*_*435 5 c++ linux file-io

如何使用C++将文件从一个文件夹复制到另一个文件夹?

Cap*_*liC 11

这应该是所需的最小代码:

#include <fstream>

// copy in binary mode
bool copyFile(const char *SRC, const char* DEST)
{
    std::ifstream src(SRC, std::ios::binary);
    std::ofstream dest(DEST, std::ios::binary);
    dest << src.rdbuf();
    return src && dest;
}

int main(int argc, char *argv[])
{
    return copyFile(argv[1], argv[2]) ? 0 : 1;
}
Run Code Online (Sandbox Code Playgroud)

它掩盖了一些可能复杂的问题:错误处理,文件名字符编码......但可以给你一个开始.


Roi*_*ton 6

std::filesystem::copy_file从C++ 17:

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

namespace fs = std::filesystem;

int main()
{
    fs::path sourceFile = "path/to/sourceFile.ext";
    fs::path targetParent = "path/to/target";
    auto target = targetParent / sourceFile.filename(); // sourceFile.filename() returns "sourceFile.ext".

    try // If you want to avoid exception handling, then use the error code overload of the following functions.
    {
        fs::create_directories(targetParent); // Recursively create target directory if not existing.
        fs::copy_file(sourceFile, target, fs::copy_options::overwrite_existing);
    }
    catch (std::exception& e) // Not using fs::filesystem_error since std::bad_alloc can throw too.  
    {
        std::cout << e.what();
    }
}
Run Code Online (Sandbox Code Playgroud)

我习惯于std::filesystem::path::filename检索源文件名,而不必手动输入.但是,std::filesystem::copy您可以省略将文件名传递到目标路径:

fs::copy(sourceFile, targetParent, fs::copy_options::overwrite_existing);
Run Code Online (Sandbox Code Playgroud)

使用更改两个函数的行为std::filesystem::copy_options.


jjl*_*lin 2

如果您愿意使用 Boost C++ 库,请查看filesystem::copy_file()

这是之前涉及 copy_file() 的问题:

如何在 boost::filesystem 中使用 copy_file ?

  • 现在,自 c++14 以来,copy_file 是 c++ start 的一部分。 (2认同)