C++17中的std::filesystem如何使用?(文件目录操作)

c++kquote>std::filesystem 是 C++17 引入的跨平台文件系统库,提供 path 操作、存在性判断、目录遍历、增删改查等安全接口,需包含头文件、处理命名空间并注意编译器链接要求。

std::filesystem 是 C++17 引入的标准库模块,用于跨平台的文件和目录操作。它替代了过去依赖系统 API 或 Boost.Filesystem 的做法,接口清晰、类型安全、异常友好。

基础准备:包含头文件与命名空间

使用前需包含头文件并处理命名空间:

#include
using namespace std::filesystem;

注意:某些编译器(如 GCC 8+、Clang 7+、MSVC 2017 Update 5+)默认支持,但 GCC 需链接 -lstdc++fs(CMake 中加 target_link_libraries(target stdc++fs))。

路径操作:path 对象是核心

所有操作都围绕 std::filesystem::path 展开,它自动处理不同系统的路径分隔符(/ 或 \):

  • 构造路径:path p = "data/config.txt";path p("logs", "app.log");
  • 拼接路径:p /= "backup";p = p / "v2" / "temp.dat";
  • 获取部分路径:p.parent_path()p.filename()p.extension()
  • 标准化路径:canonical(p)(解析 . 和 ..,需路径存在)或 weakly_canonical(p)(即使部分不存在也尝试规整)

判断与查询:检查文件系统状态

用 exists()、is_regular_file()、is_directory() 等函数快速判断:

  • if (exists("config.json")) { ... }
  • if (is_directory("src/")) { ... }
  • if (is_regular_file("log.txt") && file_size("log.txt") > 1024) { ... }
  • 获取信息:last_write_time(p) 返回 file_time_type;file_size(p) 返回 uintmax_t 字节大小

创建、复制与删除:常用文件目录管理

这些操作默认抛出 filesystem_error 异常,也可用带 error_code 参数的重载避免异常:

  • 创建目录:create_directory("build");(仅一级),create_directories("a/b/c");(递归创建)
  • 复制文件:copy_file("src.txt", "dst.txt", copy_options::overwrite_existing);
  • 重命名/移动:rename("old.log", "new.log");
  • 删除:remove("temp.bin");(文件或空目录),remove_all("cache/");(递归删除整个目录树)

遍历目录:directory_iterator 与 recursive_directory_iterator

类似 STL 迭代器风格,支持范围 for:

  • 单层遍历:for (const auto& entry : directory_iterator("src")) { cout
  • 递归遍历:for (const auto& entry : recursive_directory_iterator("project")) { ... }
  • 跳过符号链接(默认不跟随):recursive_directory_iterator(p, directory_options::skip_permission_denied)
  • entry.path() 返回完整路径,entry.is_regular_file() 等可进一步判断类型

基本上就这些。实际使用时注意权限、路径存在性、异常处理,多数操作都有非抛出版本(带 std::error_code& 参数),适合嵌入式或容错要求高的场景。