名稱空間
變體
操作

std::filesystem::remove, std::filesystem::remove_all

來自 cppreference.com
 
 
 
定義於標頭檔案 <filesystem>
bool remove( const std::filesystem::path& p );
(1) (C++17 起)
bool remove( const std::filesystem::path& p, std::error_code& ec ) noexcept;
(2) (C++17 起)
std::uintmax_t remove_all( const std::filesystem::path& p );
(3) (C++17 起)
(4) (C++17 起)
1,2) 透過路徑 p 標識的檔案或空目錄被刪除,如同透過 POSIX remove。不跟蹤符號連結(移除符號連結,而不是其目標)。
3,4) 刪除 p 的內容(如果它是一個目錄)及其所有子目錄的內容,遞迴進行,然後刪除 p 本身,如同透過重複應用 POSIX remove。不跟蹤符號連結(移除符號連結,而不是其目標)。

目錄

[編輯] 引數

p - 要刪除的路徑
ec - 用於在不丟擲異常的過載中報告錯誤的輸出引數。

[編輯] 返回值

1,2) 如果檔案被刪除則為 true,如果檔案不存在則為 false。接受 error_code& 引數的過載在錯誤時返回 false
3,4) 返回被刪除的檔案和目錄的數量(如果 p 最初不存在,則可能為零)。接受 error_code& 引數的過載在錯誤時返回 static_cast<std::uintmax_t>(-1)

[編輯] 異常

任何未標記為 noexcept 的過載都可能在記憶體分配失敗時丟擲 std::bad_alloc

1,3) 在底層 OS API 錯誤時丟擲 std::filesystem::filesystem_error,構造時將 p 作為第一個路徑引數,OS 錯誤碼作為錯誤碼引數。
2,4) 如果 OS API 呼叫失敗,則將 std::error_code& 引數設定為 OS API 錯誤碼;如果沒有發生錯誤,則執行 ec.clear()

[編輯] 注意

在 POSIX 系統上,此函式通常會根據需要呼叫 unlinkrmdir,在 Windows 上呼叫 DeleteFileWRemoveDirectoryW

如果 p 不存在,此函式返回 false 且不報告錯誤。

[編輯] 示例

#include <cstdint>
#include <filesystem>
#include <fstream>
#include <iostream>
 
int main()
{
    namespace fs = std::filesystem;
    std::cout << std::boolalpha;
 
    fs::path tmp{std::filesystem::temp_directory_path()};
 
    const auto O_O{"O_O"};
    std::ofstream{tmp / O_O} << O_O; // creates file containing O_O
    std::cout << "remove(): " << fs::remove(tmp / O_O) << '\n'; // success
    std::cout << "remove(): " << fs::remove(tmp / O_O) << '\n'; // fail
 
    std::filesystem::create_directories(tmp / "abcdef/example");
    const std::uintmax_t n{fs::remove_all(tmp / "abcdef")};
    std::cout << "remove_all(): " << n << " files or directories\n";
}

可能的輸出

remove(): true
remove(): false
remove_all(): 2 files or directories

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 3014 C++17 remove_allerror_code 過載被標記為 noexcept 但可以分配記憶體 noexcept 已移除

[編輯] 參閱

擦除檔案
(函式) [編輯]