auto p = std::filesystem::path("/home/user") / "docs" / "file.txt";
std::cout
std::cout
std::cout
std::cout
std::cout
检查文件与目录状态
使用 std::filesystem::status 和相关函数判断路径类型和权限:
std::filesystem::path p{"example.txt"};
if (std::filesystem::exists(p)) {
std::cout
if (std::filesystem::is_regular_file(p))
std::cout
if (std::filesystem::is_directory(p))
std::cout
} else {
std::cout
}
创建与删除目录
常用函数:
-
create_directory(path):创建单个目录
-
create_directories(path):递归创建多级目录
-
remove(path):删除文件或空目录
-
remove_all(path):递归删除目录及其内容
示例:
std::filesystem::create_directory("new_folder");
std::filesystem::create_directories("a/b/c/d"); // 自动创建中间目录
std::filesystem::remove("new_folder"); // 删除空目录
std::filesystem::remove_all("a"); // 删除整个 a 目录树
遍历目录内容
使用 std::filesystem::directory_iterator 遍历目录中的条目:
for (const auto& entry : std::filesystem::directory_iterator(".")) {
std::cout
if (entry.is_regular_file())
std::cout
else if (entry.is_directory())
std::cout
std::cout
}
若需递归遍历,使用 recursive_directory_iterator:
for (const auto& entry : std::filesystem::recursive_directory_iterator("mydir")) {
std::cout
}
文件操作:复制、重命名、删除
std::filesystem 提供了高层文件操作函数:
// 复制文件
std::filesystem::copy("source.txt", "backup.txt");
// 复制目录(需目标目录不存在或为空)
std::filesystem::copy("src_dir", "dst_dir", std::filesystem::copy_options::recursive);
// 重命名/移动
std::filesystem::rename("old_name.txt", "new_name.txt");
// 删除文件
std::filesystem::remove("temp.txt");
可指定选项控制行为,例如跳过已存在文件、只复制更新的文件等。
获取文件大小与时间信息
通过 file_size 和 last_write_time 获取元数据:
uintmax_t size = std::filesystem::file_size("data.bin");
std::cout
auto time = std::filesystem::last_write_time("data.bin");
// 转为可读时间格式(需转换时区等)
auto sctp = std::chrono::time_point_cast<:chrono::seconds>(time);
std::time_t tt = std::chrono::system_clock::to_time_t(sctp);
std::cout
小结与注意事项
std::filesystem 极大简化了C++中的文件系统编程。使用时注意:
- 确保编译器支持 C++17 并开启对应标准
- 某些函数可能抛出 std::filesystem::filesystem_error,建议用 try-catch 包裹
- 路径最好使用 std::filesystem::path 对象管理,避免字符串拼接错误
- 跨平台时注意权限、符号链接等差异
基本上就这些。熟练掌握后,写跨平台文件管理工具会轻松很多。