在C++17之前,处理文件系统往往需要依赖操作系统的API或第三方库,例如POSIX的dirent.h、Windows的<windows.h>或Boost.Filesystem。随着标准化的推进,std::filesystem被引入到C++17标准库中,提供了跨平台、类型安全且易于使用的文件系统接口。本文将系统性地介绍std::filesystem的核心功能、常见使用场景以及如何利用它提升项目的可靠性与可维护性。
1. 基础概念
std::filesystem定义在`
`头文件中,命名空间为`std::filesystem`(或`std::experimental::filesystem`在C++17早期实现)。核心类主要包括:
– `std::filesystem::path`:跨平台路径对象,支持字符串拼接、提取文件名、扩展名等操作。
– `std::filesystem::directory_entry`:表示目录中的单个条目,包含路径、属性等信息。
– `std::filesystem::directory_iterator`:目录迭代器,支持范围基于循环遍历目录。
## 2. 常用操作
### 2.1 创建与删除
“`cpp
#include
namespace fs = std::filesystem;
// 创建单层目录
fs::create_directory(“log”);
// 创建多层目录
fs::create_directories(“data/tmp”);
// 删除文件
fs::remove(“old.log”);
// 删除目录(需为空)
fs::remove(“log”);
// 删除目录及其子内容
fs::remove_all(“data”);
“`
### 2.2 复制与移动
“`cpp
// 复制文件,保留属性
fs::copy_file(“source.txt”, “dest.txt”, fs::copy_options::overwrite_existing);
// 复制目录(递归)
fs::copy(“src_dir”, “dst_dir”, fs::copy_options::recursive | fs::copy_options::overwrite_existing);
// 移动文件
fs::rename(“tmp.txt”, “archive/tmp.txt”);
“`
### 2.3 查询与遍历
“`cpp
// 检查是否存在
if (fs::exists(“config.yaml”)) {
std::cout