請參閱下面的代碼,以及下面的錯誤。
std::string source = "C:\\Users\\cambarchian\\Documents\\tested";
std::string destination = "C:\\Users\\cambarchian\\Documents\\tester";
std::filesystem::path sourcepath = source;
std::filesystem::path destpath = destination;
std::filesystem::copy_options::update_existing;
std::filesystem::copy(sourcepath, destpath);
terminate called after throwing an instance of 'std::filesystem::__cxx11::filesystem_error'
what(): filesystem error: cannot copy: File exists [C:\Users\cambarchian\Documents\tested] [C:\Users\cambarchian\Documents\tester]
嘗試使用 filesystem::copy,以及嘗試不同的路徑。任何事情都沒有運氣。我不能在這里寫太多,因為上面列出了問題,可能是一個簡單的格式問題。話雖如此,它在我的家用電腦上使用了 Visual Studio 2022,但是使用 VS Code 和 gcc 11.2 給了我這個問題。
uj5u.com熱心網友回復:
使用: filesystem::copy_file(oldPath, newPath, filesystem::copy_options::overwrite_existing);
uj5u.com熱心網友回復:
的多載std::filesystem::copy記錄在案。您正在使用第一個多載,但想要第二個:
void copy(from, to)這相當于 [overload 2, below] 使用copy_options::nonevoid copy(from, to, options)
在呼叫 copy 之前撰寫陳述句std::filesystem::copy_options::update_existing;根本沒有任何效果,而將選項傳遞給正確的多載,例如
std::filesystem::copy(sourcepath, destpath,
std::filesystem::copy_options::update_existing);
應該做你想做的。
...它使用 Visual Studio 2022 在我的家用電腦上運行...
您沒有說在這種情況下目標檔案是否存在,這是您應該檢查的第一件事。
我將 copy_options 放在 copy 函式中,但它不起作用,所以我開始移動它,我可能應該提到這一點。
隨機排列代碼并不是生成干凈示例供他人幫助的好方法。
在極少數情況下,破解某些東西確實可以解決它,我強烈建議停下來找出原因。當你破解了某些東西但它仍然不起作用時,一定要留下評論來提醒自己你嘗試了什么,但代碼本身應該仍然處于良好狀態。
寫的時候還是不行
std::filesystem::copy(sourcepath, destpath, std::filesystem::copy_options::recursive)
嗯,這是一個不同的選擇,不是嗎?你是否也隨機排列了copy_options你選擇的那個?
嘗試 recursive 和 update_existing 會產生相同的問題。
檔案說
options如果存在于(甚至在組中)的任何 copy_options 選項組中存在多個選項,則行為未定義copy_file。
所以你不應該同時設定兩者。遞回復制單個檔案沒有任何好處,但更新或覆寫檔案可能有好處。如果目的地已經存在。根據您的錯誤,確實如此。
由于您確實有一個錯誤明確指出“檔案存在”,因此您當然應該查看此處表格的“控制copy_file()檔案何時已存在的選項”部分。
uj5u.com熱心網友回復:
Visual Studio 2022 修復了該問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/457519.html
