C++标准库头文件 filesystem 举例说明

C++标准库头文件 filesystem 举例说明

1. <filesystem>

<filesystem> 是 C++17 引入的标准库头文件,提供了一套跨平台的 文件系统操作接口,可以方便地处理文件路径、目录遍历、文件信息查询等操作。以下是 核心功能及代码示例:

1. 核心类和函数

组件 用途
std::filesystem::path 表示文件路径(跨平台兼容,自动处理 / 和 \ 转换)
std::filesystem::directory_entry 表示目录中的文件/子目录信息(如大小、类型)
std::filesystem::directory_iterator 遍历目录内容
fs::exists() 检查文件/目录是否存在
fs::create_directory() 创建目录
fs::copy() 复制文件/目录
fs::remove() 删除文件
fs::file_size() 获取文件大小(字节)
fs::last_write_time() 获取文件的最后修改时间

2. 代码示例

(1) 路径操作 (std::filesystem::path)

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;  // 简化命名空间

int main() {
    fs::path p1 = "C:/Users/Alice/data.txt";  // Windows 风格
    fs::path p2 = "/home/bob/data.txt";       // Linux 风格

    // 路径拼接
    fs::path p3 = p1.parent_path() / "new_data.txt";
    std::cout << "New path: " << p3 << "\n";  // 输出: C:\Users\Alice\new_data.txt

    // 获取文件名/扩展名
    std::cout << "Filename: " << p1.filename() << "\n";    // data.txt
    std::cout << "Extension: " << p1.extension() << "\n";  // .txt

    return 0;
}
===============================================
New path: "C:/Users/Alice/new_data.txt"
Filename: "data.txt"
Extension: ".txt"
===============================================

(2) 检查文件/目录是否存在
if (fs::exists("test.txt")) {
    std::cout << "File exists!\n";
} else {
    std::cout << "File not found.\n";
}

(3) 遍历目录
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;

int main() {
    std::string dir_path = "./example_dir";

    // 创建目录(如果不存在)
    if (!fs::exists(dir_path)) {
        fs::create_directory(dir_path);
    }

    // 遍历目录
    for (const auto& entry : fs::directory_iterator(dir_path)) {
        std::cout << "Found: " << entry.path() << "\n";
        if (entry.is_regular_file()) {
            std::cout << "  Size: " << fs::file_size(entry) << " bytes\n";
        }
    }

    return 0;
}

=========================================================
输出(假设 example_dir 下有一个文件 a.txt):
Found: "./example_dir/a.txt"
  Size: 1024 bytes
=========================================================

(4) 复制/删除文件
fs::path src = "source.txt";
fs::path dst = "backup.txt";

// 复制文件
fs::copy(src, dst, fs::copy_options::overwrite_existing);  // 覆盖已存在文件

// 删除文件
if (fs::remove(dst)) {
    std::cout << "File deleted.\n";
}

(5) 获取文件信息
fs::path file = "data.bin";

if (fs::exists(file)) {
    auto size = fs::file_size(file);  // 文件大小(字节)
    auto time = fs::last_write_time(file);  // 最后修改时间

    std::cout << "Size: " << size << " bytes\n";
    std::cout << "Last modified: " << time.time_since_epoch().count() << "\n";
}

3. 跨平台路径处理
std::filesystem::path 自动适配操作系统:
Windows:默认使用 \,但 / 也支持。
Linux/macOS:使用 /。

实例:

fs::path p1 = "C:\\Windows\\System32\\cmd.exe";  // Windows 反斜杠
fs::path p2 = "/usr/bin/bash";                   // Linux 正斜杠

// 统一转换为字符串(自动适应平台)
std::string win_path = p1.string();   // "C:\\Windows\\System32\\cmd.exe"
std::string unix_path = p2.string();  // "/usr/bin/bash"

4. 错误处理
使用 std::filesystem::filesystem_error 捕获异常:

try {
    fs::copy("nonexistent.txt", "copy.txt");
} catch (const fs::filesystem_error& e) {
    std::cerr << "Error: " << e.what() << "\n";
    std::cerr << "Path: " << e.path1() << "\n";
}

================================================
输出(如果文件不存在):
Error: filesystem error: cannot copy: No such file or directory [...]
Path: "nonexistent.txt"
================================================

5. 典型应用场景
配置文件管理
检查配置文件是否存在,若不存在则创建默认配置。
日志系统
自动创建日志目录,按日期分割日志文件。
资源加载
遍历资源目录加载游戏素材或插件。
数据备份
复制/移动文件到备份目录。

6. 注意事项
C++17 支持
编译器需支持 C++17(如 GCC 7+、Clang 5+、MSVC 2017+)。
编译时需链接 stdc++fs(GCC)或 c++fs(Clang):

g++ -std=c++17 main.cpp -lstdc++fs

权限问题
某些操作(如删除系统文件)可能需要管理员权限。
符号链接
使用 fs::is_symlink() 和 fs::read_symlink() 处理符号链接。

总结
提供了 跨平台、类型安全 的文件系统操作接口,适合:

  • 路径处理(自动适配 Windows/Linux)
  • 目录遍历
  • 文件信息查询
  • 复制/移动/删除文件
  • 如果需要更复杂的操作(如递归遍历目录或文件监控),可以结合 和多线程实现。
posted @ 2025-04-28 11:45  michaelchengjl  阅读(429)  评论(0)    收藏  举报