C ++ 17文件系统copy_file访问被拒绝

Ken*_*tro -1 c++ filesystems c++17

我正在使用 Visual Studio 2017,运行 c++17 ISO 标准(不是 boost)设置为能够使用<filesystem>. 不过,我遇到了麻烦,因为每次运行时,无论是在调试还是发布中,file_copy()都会出现访问被拒绝的错误。我检查了代码的其他部分,唯一不起作用的是file_copy(). 有谁知道我为什么会收到此错误以及如何修复它?我是我电脑上的管理帐户。

std::vector<std::string> findAndCopyFiles()
{
    std::vector<std::string> fileNames;
    std::error_code errCode;
    errCode.clear();

    fs::current_path("C:\\Users\\kenny\\Desktop\\Engine", errCode);
    std::cout << errCode.message() << std::endl; errCode.clear();

    fs::path pa = fs::current_path();
    pa += "\\TEMP";
    std::cout << pa.string() << std::endl;

    if (fs::create_directory(pa, errCode))//Create directory for copying all files)
    {
        std::cout << "Directory created successfully" << std::endl;
        std::cout << errCode.message() << std::endl; errCode.clear();
    }
    fs::path tempDir(pa);
    fs::path currentDirectory = fs::current_path();
    fs::recursive_directory_iterator dirIter(currentDirectory);
    for (auto &p : dirIter)
    {
        if (p.path().extension() == ".cpp" || p.path().extension() == ".h")
        {
            //std::string fileContents = getFileContents(p.path().string());

            std::string fileName = p.path().stem().string();
            if (!fs::copy_file(p.path(), tempDir, fs::copy_options::overwrite_existing, errCode))
            {
                std::cout << "failed to copy file: " << fileName << " from " << p.path().string() << " to " << tempDir.string() <<std::endl;
            }
            std::cout << errCode.message() << std::endl; errCode.clear();

            //ensures file is a cpp file before adding it to list of fileNames
            if (p.path().extension().string() == ".cpp")
            {
                auto it = std::find(fileNames.begin(), fileNames.end(), fileName); //seaches TEMP folder for file
                if (it == fileNames.end())
                {//if file was not found in vector of registered file names, add it
                    fileNames.push_back(fileName);
                }
            }
        }
    }
    std::cout << "All files found. " << fileNames.size() << " files were found" << std::endl;
    return fileNames;
}
Run Code Online (Sandbox Code Playgroud)

G.M*_*.M. 5

根据评论。您试图用常规文件覆盖目录。来自文档[已修剪]

o Otherwise, if the destination file already exists...
  o Report an error if any of the following is true:
    o to and from are the same as determined by equivalent(from, to);
    o to is not a regular file as determined by !is_regular_file(to)
Run Code Online (Sandbox Code Playgroud)

因此,您需要使用`std::filesystem::operator/重载(未经测试)将文件名附加到目标目录路径...

if (!fs::copy_file(p.path(), tempDir / p.filename(), fs::copy_options::overwrite_existing, errCode))
Run Code Online (Sandbox Code Playgroud)