std::experimental::filesystem::copy_file
來自 cppreference.com
< cpp | experimental | fs
定義於標頭檔案 <experimental/filesystem> |
||
bool copy_file( const path& from, const path& to ); bool copy_file( const path& from, const path& to, error_code& ec ); |
(1) | (檔案系統 TS) |
bool copy_file( const path& from, const path& to, copy_options options ); bool copy_file( const path& from, const path& to, copy_options options, error_code& ec ); |
(2) | (檔案系統 TS) |
1) 預設情況,等同於使用
copy_options::none
作為 options 的 (2)。2) 使用 options 指示的複製選項,將單個檔案從 from 複製到 to。如果在 options 中存在任何 copy_options 選項組中(即使是不與
copy_file
相關的組)有多個選項,則行為未定義。- 如果目標檔案不存在,
- 將 from 解析到的檔案的內容和屬性複製到 to 解析到的檔案(符號連結被跟蹤)。
- 否則,如果目標檔案已存在
- 如果 to 和 from 透過 equivalent(from, to) 確定為相同,則報告錯誤。
- 否則,如果在 options 中沒有設定任何 copy_file 控制選項,則報告錯誤。
- 否則,如果在 options 中設定了
copy_options::skip_existing
,則不執行任何操作。 - 否則,如果在 options 中設定了
copy_options::overwrite_existing
,則將 from 解析到的檔案的內容和屬性複製到 to 解析到的檔案。 - 否則,如果在 options 中設定了
copy_options::update_existing
,則僅當 from 比 to 新時才複製檔案,如 last_write_time() 所定義。
如果發生錯誤,非丟擲過載返回 false。
目錄 |
[編輯] 引數
from | - | 原始檔的路徑 |
to | - | 目標檔案的路徑 |
ec | - | 非丟擲過載中用於錯誤報告的出參 |
[編輯] 返回值
如果檔案已複製,則為 true,否則為 false。
[編輯] 異常
不接受 error_code& 引數的過載在底層 OS API 錯誤時丟擲 filesystem_error,該異常以 from 作為第一個引數,to 作為第二個引數,OS 錯誤碼作為錯誤碼引數構造。如果記憶體分配失敗,可能會丟擲 std::bad_alloc。接受 error_code& 引數的過載在 OS API 呼叫失敗時將其設定為 OS API 錯誤碼,並且在沒有錯誤發生時執行 ec.clear()。此過載具有noexcept 規範:
noexcept
[編輯] 注意
這些函式最多包含一次直接或間接呼叫 status(to)(用於確定檔案是否存在,以及對於 copy_options::update_existing
選項,確定其最後寫入時間)。
當使用 copy_file
複製目錄時會報告錯誤:請使用 copy。
copy_file
遵循符號連結:請使用 copy_symlink 或 copy 並結合 copy_options::copy_symlinks
。
[編輯] 示例
執行此程式碼
#include <experimental/filesystem> #include <fstream> #include <iostream> namespace fs = std::experimental::filesystem; int main() { fs::create_directory("sandbox"); std::ofstream("sandbox/file1.txt").put('a'); fs::copy_file("sandbox/file1.txt", "sandbox/file2.txt"); // now there are two files in sandbox: std::cout << "file1.txt holds : " << std::ifstream("sandbox/file1.txt").rdbuf() << '\n'; std::cout << "file2.txt holds : " << std::ifstream("sandbox/file2.txt").rdbuf() << '\n'; // fail to copy directory fs::create_directory("sandbox/abc"); try { fs::copy_file("sandbox/abc", "sandbox/def"); } catch (fs::filesystem_error& e) { std::cout << "Could not copy sandbox/abc: " << e.what() << '\n'; } fs::remove_all("sandbox"); }
可能的輸出
file1.txt holds : a file2.txt holds : a Could not copy sandbox/abc: copy_file: Is a directory: "sandbox/abc", "sandbox/def"
[編輯] 另請參閱
指定複製操作的語義 (列舉) | |
複製一個符號連結 (函式) | |
複製檔案或目錄 (函式) |