filesystem
std::filesystem 是 C++17 引入的跨平台文件系统库,提供了统一的目录遍历、路径操作、文件状态查询等能力。在此之前,C++ 没有标准的方式来操作文件路径和目录,必须依赖平台 API(Windows 的 FindFirstFile、POSIX 的 opendir 等)。
头文件与基本特征
#include <filesystem>
| 特征 | 说明 |
|---|---|
| 核心类型 | path(路径)、directory_entry(目录项) |
| 路径操作 | 拼接、拆分、标准化、扩展名提取 |
| 目录遍历 | directory_iterator(非递归)、recursive_directory_iterator(递归) |
| 文件状态 | exists()、is_directory()、file_size() 等 |
| 操作函数 | create_directory()、copy()、remove()、rename() 等 |
基本用法
路径操作
#include <filesystem>
#include <iostream>
int main() {
namespace fs = std::filesystem;
fs::path p = "C:/Users/doc/readme.txt";
std::cout << "filename: " << p.filename() << '\n'; // readme.txt
std::cout << "extension: " << p.extension() << '\n'; // .txt
std::cout << "stem: " << p.stem() << '\n'; // readme
std::cout << "parent: " << p.parent_path() << '\n'; // C:/Users/doc
return 0;
}
遍历目录
#include <filesystem>
#include <iostream>
int main() {
namespace fs = std::filesystem;
fs::path dir = "."; // 当前目录
for (const fs::directory_entry& entry : fs::directory_iterator(dir)) {
std::cout << entry.path().filename() << '\n';
}
return 0;
}
递归遍历
for (const fs::directory_entry& entry : fs::recursive_directory_iterator(dir)) {
std::cout << entry.path() << '\n';
}
常用接口
| 函数/类型 | 作用 |
|---|---|
path | 路径类型,跨平台表示 |
operator/ | 路径拼接 auto p = dir / "sub" / "file.txt" |
exists(p) | 判断路径是否存在 |
is_directory(p) / is_regular_file(p) | 判断类型 |
file_size(p) | 文件大小 |
create_directory(p) | 创建目录 |
copy(from, to) | 复制文件/目录 |
remove(p) | 删除文件/空目录 |
rename(from, to) | 重命名/移动 |
current_path() | 当前工作目录 |
使用注意
filesystem操作的异常默认为抛出fs::filesystem_error,也可用std::error_code重载避免异常。- 路径拼接直接用
/运算符:auto p = base / "sub" / "file"。 - 在 Windows 和 Linux 上路径分隔符自动处理,不需手动
\\和/转换。 recursive_directory_iterator可能抛出filesystem_error(权限不足等),建议 try/catch。
小结
std::filesystem 终于让 C++ 有了原生的跨平台文件系统操作能力。路径用 path 类型,遍历用 directory_iterator,常用操作以自由函数提供。是新项目中替代平台文件 API 的首选方案。