std::filesystem
是 C++17 引入的标准库,用于处理文件系统操作,提供了跨平台的文件和目录操作能力。以下是一些常用的函数和类:
一、路径操作(std::filesystem::path
)
cpp
运行
#include <filesystem>
namespace fs = std::filesystem;// 路径构造与分解
fs::path p = "C:/data/file.txt";
p.parent_path(); // 返回目录路径:"C:/data"
p.filename(); // 返回文件名:"file.txt"
p.stem(); // 返回文件名(不含扩展名):"file"
p.extension(); // 返回扩展名:".txt"// 路径拼接
p /= "subdir"; // 拼接路径:"C:/data/subdir"
p.append("newfile"); // 等价于 p /= "newfile"// 规范化路径
p.normalize(); // 解析 ".." 和 ".",简化路径
p.lexically_normal(); // 仅做字符串处理,不检查文件系统
二、文件 / 目录状态检查
cpp
运行
fs::exists(p); // 文件或目录是否存在
fs::is_regular_file(p); // 是否为普通文件
fs::is_directory(p); // 是否为目录
fs::is_symlink(p); // 是否为符号链接
fs::is_empty(p); // 文件是否为空或目录是否为空
fs::file_size(p); // 文件大小(字节)
fs::last_write_time(p); // 最后修改时间
三、文件操作
cpp
运行
// 创建/删除文件
fs::create_directory("new_dir"); // 创建单个目录
fs::create_directories("a/b/c"); // 递归创建目录
fs::remove("file.txt"); // 删除文件或空目录
fs::remove_all("dir"); // 递归删除目录及其内容// 文件属性
fs::permissions(p, fs::perms::add_write); // 添加写权限
fs::copy_file("src.txt", "dst.txt"); // 复制文件
fs::rename("old.txt", "new.txt"); // 重命名文件
四、目录遍历
cpp
运行
// 范围-based for 遍历目录
for (const auto& entry : fs::directory_iterator("dir")) {if (entry.is_regular_file()) {std::cout << "文件: " << entry.path() << std::endl;}
}// 递归遍历(C++17)
for (const auto& entry : fs::recursive_directory_iterator("dir")) {std::cout << entry.path() << std::endl;
}// 过滤特定类型的文件
for (const auto& entry : fs::directory_iterator("dir")) {if (entry.path().extension() == ".txt") {// 处理 .txt 文件}
}
五、文件时间与权限
cpp
运行
// 文件时间戳
auto time = fs::last_write_time(p);
fs::last_write_time(p, std::filesystem::file_time_type::clock::now()); // 更新时间// 文件权限(POSIX风格)
fs::permissions(p, fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read);
六、错误处理
cpp
运行
// 异常安全版本(默认)
try {fs::create_directory("test");
} catch (const fs::filesystem_error& e) {std::cerr << "错误: " << e.what() << "\n路径: " << e.path1() << std::endl;
}// 错误码版本(非抛出)
std::error_code ec;
fs::create_directory("test", ec);
if (ec) {std::cerr << "错误码: " << ec.value() << ", " << ec.message() << std::endl;
}
七、跨平台注意事项
-
路径分隔符:
- 使用原始字符串字面量避免转义问题:
R"(C:\data\file.txt)"
- 或使用斜杠(
/
),std::filesystem
会自动转换为平台特定格式
- 使用原始字符串字面量避免转义问题:
-
环境兼容性:
- Windows:支持 UNC 路径(如
\\server\share\file.txt
) - Linux/macOS:支持符号链接和硬链接
- Windows:支持 UNC 路径(如
八、示例:计算目录大小
cpp
运行
uintmax_t calculateDirectorySize(const fs::path& dir) {uintmax_t size = 0;for (const auto& entry : fs::recursive_directory_iterator(dir)) {if (entry.is_regular_file()) {size += entry.file_size();}}return size;
}
九、兼容性说明
- C++17:完整支持
std::filesystem
- C++14:实验性版本
std::experimental::filesystem
- GCC/Clang:需要链接
-lstdc++fs
(GCC 7-9) - MSVC:无需额外链接,确保启用
/std:c++17