std::filesystem ​

什么是 std::filesystem ​

std::filesystem 是 C++17 在 <filesystem> 头文件中引入的文件系统操作库。它提供了跨平台的路径操作、文件和目录的创建/删除/拷贝/移动、目录遍历、文件属性查询等功能。在此之前,C++ 标准库没有任何文件系统操作的支持,开发者要么用 C 语言的 fopen/remove 等函数,要么依赖平台特定的 API(Windows 的 FindFirstFile、POSIX 的 opendir 等),要么使用 Boost.Filesystem。

std::filesystem 的设计直接来源于 Boost.Filesystem,API 非常相似。整个库围绕 std::filesystem::path 类展开——它是路径的抽象表示,能自动处理不同操作系统的路径分隔符(Windows 的 \ 和 POSIX 的 /)。

所有函数和类都在 std::filesystem 命名空间下,通常用 namespace fs = std::filesystem; 做别名简化代码。

头文件与命名空间 ​

cpp
#include <filesystem>

namespace fs = std::filesystem;  // 常用别名

核心类和函数 ​

类/函数说明
fs::path路径类,支持路径拼接、分解、格式转换
fs::directory_entry目录项,包含路径和缓存的文件属性
fs::directory_iterator非递归目录遍历迭代器
fs::recursive_directory_iterator递归目录遍历迭代器
fs::exists()检查路径是否存在
fs::is_regular_file() / fs::is_directory()检查文件类型
fs::file_size()获取文件大小(字节)
fs::create_directory() / fs::create_directories()创建目录(单层/递归)
fs::remove() / fs::remove_all()删除文件/递归删除目录
fs::copy() / fs::copy_file()拷贝文件或目录
fs::rename()重命名/移动文件或目录
fs::current_path()获取/设置当前工作目录
fs::temp_directory_path()获取临时目录路径
fs::last_write_time()获取/设置最后修改时间
fs::space()获取磁盘空间信息
fs::permissions()获取/设置文件权限

基本示例 ​

cpp
#include <iostream>
#include <filesystem>
#include <fstream>
#include <string>

namespace fs = std::filesystem;

// ============================
// 示例1:path 类的基本操作
// ============================

void path_demo() {
    // 构造路径
    fs::path p1 = "C:/Users/test/documents";
    fs::path p2 = "/home/user/docs";
    fs::path p3 = "relative/path/file.txt";

    // 路径拼接(使用 / 运算符)
    fs::path p4 = p1 / "subdir" / "file.txt";
    std::cout << "拼接结果: " << p4 << std::endl;

    // 路径分解
    fs::path file = "C:/projects/src/main.cpp";
    std::cout << "根路径: " << file.root_path() << std::endl;       // "C:/"
    std::cout << "父路径: " << file.parent_path() << std::endl;     // "C:/projects/src"
    std::cout << "文件名: " << file.filename() << std::endl;        // "main.cpp"
    std::cout << "主文件名: " << file.stem() << std::endl;           // "main"
    std::cout << "扩展名: " << file.extension() << std::endl;       // ".cpp"

    // 修改扩展名
    fs::path newfile = file;
    newfile.replace_extension(".h");
    std::cout << "改扩展名: " << newfile << std::endl;  // "C:/projects/src/main.h"

    // 路径比较和判断
    std::cout << "是绝对路径? " << std::boolalpha << file.is_absolute() << std::endl;  // true
    std::cout << "是相对路径? " << p3.is_relative() << std::endl;  // true

    // 路径迭代(逐段分解)
    std::cout << "路径各段: ";
    for (const auto& part : file) {
        std::cout << "[" << part << "] ";
    }
    std::cout << std::endl;
}

// ============================
// 示例2:文件和目录的基本操作
// ============================

void file_ops_demo() {
    fs::path sandbox = fs::temp_directory_path() / "cpp17_demo";

    // 创建目录(递归创建)
    fs::create_directories(sandbox / "subdir1" / "nested");
    fs::create_directory(sandbox / "subdir2");

    std::cout << "创建的目录: " << sandbox << std::endl;

    // 创建文件
    std::ofstream(sandbox / "hello.txt") << "Hello, filesystem!";
    std::ofstream(sandbox / "data.csv") << "name,age\nalice,30\nbob,25";

    // 检查是否存在
    std::cout << "sandbox 存在? " << fs::exists(sandbox) << std::endl;         // true
    std::cout << "hello.txt 存在? " << fs::exists(sandbox / "hello.txt") << std::endl;  // true
    std::cout << "nothing.txt 存在? " << fs::exists(sandbox / "nothing.txt") << std::endl; // false

    // 检查文件类型
    std::cout << "sandbox 是目录? " << fs::is_directory(sandbox) << std::endl;          // true
    std::cout << "hello.txt 是文件? " << fs::is_regular_file(sandbox / "hello.txt") << std::endl;  // true

    // 获取文件大小
    auto size = fs::file_size(sandbox / "hello.txt");
    std::cout << "hello.txt 大小: " << size << " 字节" << std::endl;

    // 拷贝文件
    fs::copy_file(sandbox / "hello.txt", sandbox / "hello_copy.txt");
    std::cout << "拷贝完成" << std::endl;

    // 重命名
    fs::rename(sandbox / "hello_copy.txt", sandbox / "hello_renamed.txt");
    std::cout << "重命名完成" << std::endl;

    // 删除单个文件
    fs::remove(sandbox / "hello_renamed.txt");

    // 递归删除整个目录
    auto removed = fs::remove_all(sandbox);
    std::cout << "删除了 " << removed << " 个文件/目录" << std::endl;
}

// ============================
// 示例3:目录遍历
// ============================

void directory_traversal_demo() {
    fs::path sandbox = fs::temp_directory_path() / "traverse_demo";
    fs::create_directories(sandbox / "src" / "utils");
    fs::create_directory(sandbox / "build");
    std::ofstream(sandbox / "CMakeLists.txt") << "cmake_minimum_required(VERSION 3.14)";
    std::ofstream(sandbox / "src" / "main.cpp") << "int main() {}";
    std::ofstream(sandbox / "src" / "utils" / "helper.h") << "#pragma once";

    // 非递归遍历(只看第一层)
    std::cout << "=== 非递归遍历 ===" << std::endl;
    for (const auto& entry : fs::directory_iterator(sandbox)) {
        std::cout << "  ";
        if (entry.is_directory()) {
            std::cout << "[DIR] ";
        } else {
            std::cout << "[FILE " << entry.file_size() << "B] ";
        }
        std::cout << entry.path().filename() << std::endl;
    }

    // 递归遍历(深入所有子目录)
    std::cout << "=== 递归遍历 ===" << std::endl;
    for (const auto& entry : fs::recursive_directory_iterator(sandbox)) {
        // 根据深度缩进
        auto depth = std::distance(sandbox.begin(), entry.path().begin())
                   - std::distance(sandbox.begin(), sandbox.end());
        // 简单缩进
        std::cout << std::string(depth * 2, ' ');

        if (entry.is_directory()) {
            std::cout << "[DIR] " << entry.path().filename() << std::endl;
        } else {
            std::cout << entry.path().filename()
                      << " (" << entry.file_size() << " bytes)" << std::endl;
        }
    }

    // 用范围过滤:只列出 .cpp 文件
    std::cout << "=== 只列 .cpp 文件 ===" << std::endl;
    for (const auto& entry : fs::recursive_directory_iterator(sandbox)) {
        if (entry.is_regular_file() && entry.path().extension() == ".cpp") {
            std::cout << "  " << entry.path() << std::endl;
        }
    }

    fs::remove_all(sandbox);
}

// ============================
// 示例4:错误处理(两种方式)
// ============================

void error_handling_demo() {
    // 方式1:异常(默认行为)
    try {
        fs::file_size("nonexistent_file.txt");
    } catch (const fs::filesystem_error& e) {
        std::cout << "异常: " << e.what() << std::endl;
        std::cout << "路径1: " << e.path1() << std::endl;
    }

    // 方式2:error_code(不抛异常)
    std::error_code ec;
    auto size = fs::file_size("nonexistent_file.txt", ec);
    if (ec) {
        std::cout << "错误码: " << ec.message() << std::endl;
    } else {
        std::cout << "大小: " << size << std::endl;
    }
}

// ============================
// 示例5:磁盘空间信息
// ============================

void space_demo() {
    auto info = fs::space(fs::current_path());
    std::cout << "磁盘空间信息:" << std::endl;
    std::cout << "  总容量: " << info.capacity / (1024 * 1024 * 1024) << " GB" << std::endl;
    std::cout << "  可用: " << info.available / (1024 * 1024 * 1024) << " GB" << std::endl;
    std::cout << "  空闲: " << info.free / (1024 * 1024 * 1024) << " GB" << std::endl;
}

int main() {
    std::cout << "=== path 操作 ===" << std::endl;
    path_demo();

    std::cout << "\n=== 文件操作 ===" << std::endl;
    file_ops_demo();

    std::cout << "\n=== 目录遍历 ===" << std::endl;
    directory_traversal_demo();

    std::cout << "\n=== 错误处理 ===" << std::endl;
    error_handling_demo();

    std::cout << "\n=== 磁盘空间 ===" << std::endl;
    space_demo();

    return 0;
}

path 类常用操作汇总 ​

操作示例结果
拼接path("a") / "b" / "c.txt""a/b/c.txt"
获取文件名path("a/b/c.txt").filename()"c.txt"
获取主文件名path("a/b/c.txt").stem()"c"
获取扩展名path("a/b/c.txt").extension()".txt"
获取父路径path("a/b/c.txt").parent_path()"a/b"
替换扩展名path("c.txt").replace_extension(".h")"c.h"
替换文件名path("a/b/c.txt").replace_filename("d.h")"a/b/d.h"
是否绝对路径path("/usr/bin").is_absolute()true
转为字符串path("a/b").string()"a/b"
转为通用格式path("a\\b").generic_string()"a/b"

与传统方案的对比 ​

操作C++17 std::filesystem传统 C/C++平台特定 API
检查文件存在fs::exists(p)fopen 然后关闭stat()/GetFileAttributes()
获取文件大小fs::file_size(p)fseek + ftellstat()/GetFileSize()
创建目录fs::create_directories(p)无标准方法mkdir()/CreateDirectory()
遍历目录directory_iterator无标准方法opendir()/FindFirstFile()
删除文件fs::remove(p)std::remove()unlink()/DeleteFile()
路径拼接p1 / p2手动字符串拼接手动或平台函数

适用场景 ​

  • 跨平台的文件和目录操作(不再需要 #ifdef _WIN32 切换代码)
  • 构建工具和脚本中遍历目录、查找特定文件
  • 配置文件和日志文件的路径管理
  • 文件备份和同步工具
  • 清理临时文件和目录
  • 获取磁盘空间信息

常见问题 ​

fs::path 在 Windows 上用正斜杠还是反斜杠?

fs::path 内部使用操作系统的原生分隔符(Windows 用 \,POSIX 用 /)。但构造时接受两种分隔符。string() 返回原生格式,generic_string() 返回通用格式(/)。路径拼接用 / 运算符不影响最终格式。

filesystem 函数的错误处理用异常还是 error_code?

几乎所有 filesystem 函数都有两个重载:一个抛异常(fs::filesystem_error),一个接受 std::error_code& 引用参数(不抛异常)。性能敏感或错误是预期内的场景用 error_code 版本;错误是异常情况时用抛异常版本。

directory_iterator 遍历时可以修改目录内容吗?

可以,但行为是实现定义的——新添加或删除的文件是否被迭代器看到是不确定的。如果你需要在遍历时删除文件,建议先收集路径列表,遍历完再删除。

fs::path 和 std::string 怎么互转?

path 有 string() 方法返回 std::string;std::string 可以隐式构造 path。path 也支持 c_str() 返回 C 风格字符串(Windows 上返回宽字符 wchar_t*)。

注意事项 ​

  • filesystem 操作是 I/O 操作,有系统调用开销,不适合在性能关键的循环中频繁调用
  • 路径操作(拼接、分解、比较)是纯字符串操作,不访问文件系统
  • file_size() 对目录的行为是未定义的,对符号链接返回目标文件的大小
  • remove_all() 是递归删除,使用时要格外小心路径的正确性
  • Windows 上 fs::path 内部使用 wchar_t(UTF-16),string() 可能有编码转换问题,建议用 u8string() 获取 UTF-8 编码
  • directory_iterator 不保证遍历顺序
  • 符号链接和权限的行为在不同操作系统上有差异

编译器支持与链接 ​

编译器最低支持版本链接选项
GCC8.0GCC 8 需要 -lstdc++fs,GCC 9+ 不需要
Clang7.0可能需要 -lc++fs(取决于 libc++ 版本)
MSVC19.14 (VS 2017 15.7)无需额外链接

总结 ​

std::filesystem 是 C++17 最具实用价值的新增库之一,填补了 C++ 标准库长期缺失的文件系统操作能力。fs::path 类提供了跨平台的路径抽象,支持直观的 / 拼接运算符和丰富的路径分解方法。文件和目录操作函数覆盖了日常开发中的几乎所有需求:创建、删除、拷贝、移动、重命名、查询属性、遍历目录。每个函数都提供异常和 error_code 两种错误处理方式。和之前依赖平台 API 或 Boost 的做法相比,std::filesystem 是标准的、跨平台的、类型安全的。唯一需要注意的是它属于 I/O 操作,有系统调用开销,以及不同操作系统在符号链接、权限等方面的行为差异。