std::filesystem使用笔记

本文详细介绍了C++17引入的filesystem标准库,涵盖了路径判断、文件操作(如创建、删除、移动)、目录遍历、获取文件信息以及路径管理等功能,为开发者提供了处理文件系统的一站式解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++17引入了filesystem标准库,该库提供了一组类和函数,用于处理文件系统中的文件和目录。使用库,可以方便地执行文件和目录的各种操作,如创建、复制、移动、删除文件或目录,遍历目录,获取文件属性等。

1. 头文件

#include <filesystem>

2. 函数介绍

2.1. 路径判断

std::filesystem::system_complete(path);   // 返回完整路径(相对路径 + 当前路径)
std::filesystem::exists(path);   // 目录是否存在
std::filesystem::is_directory(path); // 是否是路径
std::filesystem::is_empty(path);   // 文件夹是否为空,必须保证路径存在,否则抛异常
std::filesystem::is_regular_file(path);  // 是否是普通文件
std::filesystem::is_symlink(path); // 是否是一个链接文件
std::filesystem::file_status std::filesystem::status(path);   // 返回路径名对应的状态

2.2. 路径获取

std::filesystem::initial_path();   // 得到程序运行时的系统当前路径
std::filesystem::current_path();   // 得到系统当前路径
std::filesystem::current_path(const Path& p);   // 改变当前路径
 
std::filesystem::path parentPath = p3.parent_path(); //获得父路径
std::filesystem::path parentPath = p3.system_complete(); //获得全路径(绝对路径)

2.3. 删除复制移动

std::filesystem::remove(const Path& p, system::error_code & ec = singular);   // 删除文件
std::filesystem::remove_all(const Path& p);   // 递归删除文件夹中所有内容,返回删除文件的数量,类似于rm -rf p
std::filesystem::rename(const Path1& from_p, const Path2& to_p);   // 重命名,亦可实现移动文件(夹)的功能
std::filesystem::copy_file(const Path1& from_fp, const Path2& to_fp);   // 拷贝文件

2.4. 创建路径

std::filesystem::create_directories(path) // 创建文件夹路径
std::filesystem::create_hard_link(const Path1& to_p, const Path2& from_p);  // 建立硬链接
std::filesystem::complete(const Path& p, const Path& base = initial_path<Path>());   // 以base以基,p作为相对路径,返回其完整路径
std::filesystem::create_directories(const Path & p);   // 建立路径
std::filesystem::error_code std::filesystem::create_hard_link(const Path1& to_p, const Path2& from_p, error_code& ec);   // 建立硬链接
std::filesystem::create_symlink(const Path1& to_p, const Path2& from_p);  // 建立软链接
std::filesystem::create_symlink(const Path1& to_p, const Path2& from_p, error_code& ec);   // 建立软链接
bool std::filesystem::create_directory(const Path& dp);   // 创建目录

2.5. 获取信息

std::filesystem::space_info std::filesystem::space(const Path& p);   // 得到指定路径下的空间信息,space_info 有capacity, free 和 available三个成员变量,分别表示容量,剩余空间和可用空间。
std::filesystem::last_write_time(const Path& p);   // 最后修改时间
std::filesystem::last_write_time(const Path& p, const std::time_t new_time);   // 修改最后修改时间

2.6. 路径简化

有时路径写的过于冗长,使用canonical函数可以进行简化

const std::filesystem::path file_path("/home/myname/Downloads/../../");
 
std::cout << file_path << std::endl;
std::cout << std::filesystem::canonical(file_path) << std::endl;

 输出

/home/myname/Downloads/../..
/home

3. 组合功能

3.1. 遍历文件夹

3.1.1. 遍历所有子孙目录

for (std::filesystem::directory_entry& file : std::filesystem::directory_iterator(path)) {
  if (std::filesystem::is_regular_file(file.status())) {
    std::string file_name = file.path().filename().string();
  }
}

3.1.2. 只遍历子目录

使用显示迭代器

std::filesystem::path dirpath;
std::filesystem::directory_iterator end;// 只支持本层目录遍历
for (std::filesystem::directory_iterator iter(dirpath); iter != end; iter++)
{
  std::cout << iter->leaf().string() << std::endl; // 叶结点文件名
  std::cout << iter->path().stem().string() << std::endl; // 叶结点文件名(无后缀)
  std::cout << iter->path().filename().string() << std::endl; // 文件名(不带引号)
  std::cout << iter->path().string() << std::endl; // 叶子结点路径
}

使用隐式迭代器

for (const auto& entry : std::filesystem::directory_iterator(path)) {
  if (entry.is_directory()) {
    std::cout << "一级子目录: " << entry.path().string() << std::endl;
  }
}

 3.2. 获取相对路径

std::filesystem::path p1("/user/dir");
p1.relative_path(); //获得path的相对路径

3.3. 拼接绝对路径

// 目录路径
std::filesystem::path dir_path("path/to/directory");
 
// 文件名或相对路径
std::string filename = "example.txt";
 
// 创建完整路径
std::filesystem::path full_path = dir_path / filename;

参考文献

c++中filesystem的用法是什么 - 问答 - 亿速云

boost::filesystem常用功能_is_regular_file-CSDN博客

<think>我们正在讨论C++标准库中的std::filesystem::exists函数。根据用户的问题,需要解释该函数的用途和用法。 根据引用[3]:用户提供了一个文件检测函数的示例,其中使用std::experimental::filesystem::exists(这是C++17之前的实验版本)来检测文件是否存在。 现在,在C++17及以后,std::filesystem::exists函数用于检查给定路径是否存在于文件系统中。 函数原型(简化): bool exists(const std::filesystem::path& p); bool exists(const std::filesystem::path& p, std::error_code& ec) noexcept; 第一个版本在出现错误时抛出异常,第二个版本将错误存储在ec中且不抛出异常。 使用步骤: 1. 包含头文件:<filesystem> 2. 使用命名空间:std::filesystem(或者使用完全限定名) 3. 构造一个path对象,传入要检查的路径(可以是文件或目录) 4. 调用exists函数 示例代码: 如果文件或目录存在,则返回true;否则返回false。 注意:路径可以是相对路径或绝对路径。 下面是一个简单的示例程序:</think>### C++ `std::filesystem::exists` 函数详解 #### **作用** `std::filesystem::exists` 用于检查指定路径(文件或目录)是否存在于文件系统中。其核心功能是验证路径的物理存在性,返回布尔值: - 路径存在 → 返回 `true` - 路径不存在 → 返回 `false` 此函数属于 C++17 标准库的 `<filesystem>` 头文件,定义在 `std::filesystem` 命名空间内[^1]。 --- #### **使用方法** ##### 1. **基本语法** ```cpp #include <filesystem> namespace fs = std::filesystem; // 简化命名空间 bool exists(const fs::path& p); // 抛出版本(错误时抛出异常) bool exists(const fs::path& p, std::error_code& ec) noexcept; // 无异常版本 ``` ##### 2. **参数说明** - `p`:要检查的路径(类型为 `std::filesystem::path`),支持字符串、字符串视图或 C 风格字符串隐式转换。 - `ec`(可选):错误码输出参数,用于无异常版本。若调用失败,错误信息存入 `ec`,函数返回 `false`。 ##### 3. **返回值** - `true`:路径对应的文件/目录存在。 - `false`:路径不存在或无法访问(如权限不足)。 --- #### **代码示例** ##### 示例 1:基础用法 ```cpp #include <iostream> #include <filesystem> int main() { namespace fs = std::filesystem; fs::path file_path = "test.txt"; // 相对或绝对路径 if (fs::exists(file_path)) { std::cout << "文件存在\n"; } else { std::cout << "文件不存在\n"; } return 0; } ``` ##### 示例 2:使用错误码处理异常 ```cpp #include <iostream> #include <filesystem> int main() { namespace fs = std::filesystem; fs::path dir_path = "/restricted_directory"; std::error_code ec; if (fs::exists(dir_path, ec)) { std::cout << "目录存在\n"; } else if (ec) { // 检查是否因错误导致不存在 std::cerr << "错误: " << ec.message() << '\n'; // 输出错误信息 } else { std::cout << "目录不存在\n"; } return 0; } ``` --- #### **注意事项** 1. **符号链接处理**: 若路径指向符号链接,函数检查链接指向的**目标**是否存在(而非链接本身)。 2. **权限要求**: 对目录需有**执行权限**(`x`),否则可能返回 `false`。 3. **路径规范化**: 建议配合 `std::filesystem::canonical` 或 `absolute` 使用,避免相对路径歧义[^2]: ```cpp fs::path p = "a/../b.txt"; if (fs::exists(fs::canonical(p))) { ... } // 先规范化路径 ``` 4. **跨平台兼容性**: 路径分隔符自动适配(Windows 支持 `/` 和 `\`,Linux/macOS 仅支持 `/`)。 --- #### **典型应用场景** - 文件操作前的存在性校验(如避免重复创建)。 - 安全删除前的确认(防止误删不存在的文件)。 - 动态加载资源前的路径有效性检查。 --- ### 相关问题 1. `std::filesystem::exists` 与 `std::ifstream::good` 有何区别? 2. 如何递归检查目录下所有文件的存在性? 3. 在 Windows/Linux 下处理路径时有哪些特殊注意事项? [^1]: 快速了解C++17 std::filesystem的原理和使用。 [^2]: std::filesystem使用笔记
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值