名稱空間
變體
操作

std::filesystem::is_empty

來自 cppreference.com
 
 
 
定義於標頭檔案 <filesystem>
bool is_empty( const std::filesystem::path& p );
(1) (C++17 起)
bool is_empty( const std::filesystem::path& p, std::error_code& ec );
(2) (C++17 起)

檢查給定路徑是否引用空檔案或目錄。

目錄

[編輯] 引數

p - 要檢查的路徑
ec - 錯誤情況下修改的錯誤碼

[編輯] 返回值

如果 p 指示的路徑引用空檔案或目錄,則為 true,否則為 false。如果發生錯誤,非丟擲過載返回 false

[編輯] 異常

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

1) 在底層作業系統 API 錯誤時丟擲 std::filesystem::filesystem_error,其建構函式以 p 作為第一個路徑引數,作業系統錯誤碼作為錯誤碼引數。
2) 如果作業系統 API 呼叫失敗,則將 std::error_code& 引數設定為作業系統 API 錯誤碼;如果未發生錯誤,則執行 ec.clear()

[編輯] 示例

#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iostream>
 
int main()
{
    namespace fs = std::filesystem;
 
    const fs::path tmp_dir{fs::temp_directory_path()};
    std::cout << std::boolalpha
              << "Temp dir: " << tmp_dir << '\n'
              << "is_empty(): " << fs::is_empty(tmp_dir) << '\n';
 
    const fs::path tmp_name{tmp_dir / std::tmpnam(nullptr)};
    std::cout << "Temp file: " << tmp_name << '\n';
 
    std::ofstream file{tmp_name.string()};
    std::cout << "is_empty(): " << fs::is_empty(tmp_name) << '\n';
    file << "cppreference.com";
    file.flush();
    std::cout << "is_empty(): " << fs::is_empty(tmp_name) << '\n'
              << "file_size(): " << fs::file_size(tmp_name) << '\n';
    file.close();
    fs::remove(tmp_name);
}

可能的輸出

Temp dir: "/tmp"
is_empty(): false
Temp file: "/tmp/fileCqd9DM"
is_empty(): true
is_empty(): false
file_size(): 16

[編輯] 缺陷報告

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

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

[編輯] 參閱

(C++17)(C++17)
確定檔案屬性
確定檔案屬性,檢查符號連結目標
(函式) [編輯]
(C++17)
檢查路徑是否引用現有檔案系統物件
(函式) [編輯]