跳到主要内容
版本:1.0

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()当前工作目录

使用注意

  1. filesystem 操作的异常默认为抛出 fs::filesystem_error,也可用 std::error_code 重载避免异常。
  2. 路径拼接直接用 / 运算符:auto p = base / "sub" / "file"
  3. 在 Windows 和 Linux 上路径分隔符自动处理,不需手动 \\/ 转换。
  4. recursive_directory_iterator 可能抛出 filesystem_error(权限不足等),建议 try/catch。

小结

std::filesystem 终于让 C++ 有了原生的跨平台文件系统操作能力。路径用 path 类型,遍历用 directory_iterator,常用操作以自由函数提供。是新项目中替代平台文件 API 的首选方案。