簡體   English   中英

C++ 17 文件系統 copy_file 訪問被拒絕

[英]c++ 17 filesystem copy_file access denied

我正在使用visual studio 2017,運行c++17 ISO標准(不是boost)設置為能夠使用<filesystem> 不過,我遇到了一堵牆,因為每次我運行時,無論是在調試還是發布中, file_copy()都會給我錯誤訪問被拒絕。 我檢查了我的代碼的其他部分,唯一不起作用的是file_copy() 有誰知道我為什么會收到這個錯誤以及如何解決它? 我是我 PC 上的管理帳戶。

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;
}

根據評論。 您試圖用常規文件覆蓋目錄。 文檔[修剪]

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)

因此,您需要使用`std::filesystem::operator/重載(未經測試)將文件名附加到目標目錄路徑...

if (!fs::copy_file(p.path(), tempDir / p.filename(), fs::copy_options::overwrite_existing, errCode))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM