✨博客主页 | ||
---|---|---|
何曾参静谧的博客 | ||
📌文章专栏 | ||
「C/C++」C/C++程序设计 | ||
📚全部专栏 | ||
「VS」Visual Studio | 「C/C++」C/C++程序设计 | 「UG/NX」BlockUI集合 |
「Win」Windows程序设计 | 「DSA」数据结构与算法 | 「UG/NX」NX二次开发 |
「QT」QT5程序设计 | 「File」数据文件格式 | 「PK」Parasolid函数说明 |
目录
C++中的std::filesystem::path类详解
fs::path
类是C++17标准库中文件系统库(<filesystem>
)的一部分,用于表示和操作文件系统路径。这个类提供了一系列功能,使得路径的拼接、分解、查询等操作变得简洁而高效。以下是对fs::path
类的详细介绍。
一、引言
fs::path
类是文件系统操作的基础,它封装了路径字符串,并提供了丰富的成员函数来解析、转换和操作路径。这使得开发者在处理文件路径时,能够避免很多手动字符串操作的复杂性和潜在错误。
二、使用范围
fs::path
类广泛应用于需要文件系统操作的场景中,包括但不限于:
- 文件和目录的遍历
- 路径的拼接和拆分
- 获取路径的各个组成部分(如父目录、文件名、扩展名等)
- 路径的规范化(消除冗余的
.
和..
) - 检查路径的合法性
三、类的头文件
要使用fs::path
类,需要包含头文件<filesystem>
:
#include <filesystem>
namespace fs = std::filesystem;
四、类的注意事项
- 跨平台兼容性:
fs::path
类设计时就考虑到了跨平台的需求,因此可以在不同的操作系统上(如Windows、Linux、macOS)无缝使用。 - 异常处理:某些成员函数可能会抛出异常,例如
fs::path
的构造函数在解析非法路径时。因此,在使用这些函数时,建议进行异常处理。 - 性能:
fs::path
类尽量减少了不必要的字符串复制和转换,以提供高效的性能。
五、类的继承
fs::path
类是一个最终类,不能被其他类继承。它提供了丰富的功能,已经足够满足大多数文件系统路径操作的需求。
六、类的构造介绍
fs::path
类提供了多种构造函数,允许从不同类型的输入创建路径对象:
fs::path()
: 默认构造函数,创建一个空的路径。fs::path(const std::string& s)
: 从std::string
对象创建路径。fs::path(const char* s)
: 从C风格字符串创建路径。fs::path(std::initializer_list<fs::path> init)
: 从一个初始化列表创建路径,通常用于拼接多个路径组件。
七、公有函数介绍
fs::path
类提供了大量的公有成员函数,以下是一些常用的:
string_type string() const
: 返回路径的字符串表示。parent_path() const
: 返回父目录的路径。filename() const
: 返回文件名(包括扩展名)。stem() const
: 返回文件名但不包括扩展名。extension() const
: 返回文件的扩展名。is_absolute() const
: 检查路径是否是绝对路径。is_relative() const
: 检查路径是否是相对路径。lexically_normal() const
: 返回路径的规范化表示。
八、static函数介绍
fs::path
类还提供了一些静态成员函数,用于执行路径相关的静态操作:
static std::string u8path(const fs::path& p)
: 将路径转换为UTF-8编码的字符串。static fs::path u8string(const std::string& s)
: 从UTF-8编码的字符串创建路径。
九、运算符重载
fs::path
类重载了多种运算符,使得路径操作更加直观和方便:
operator/=(const fs::path& p)
: 拼接路径。operator+=(const fs::path& p)
: 同operator/=
。operator/(const fs::path& p) const
: 返回一个新的路径,是原路径和p
的拼接结果。operator==(const fs::path& p) const
: 检查两个路径是否相等。operator!=(const fs::path& p) const
: 检查两个路径是否不相等。
十、详细代码举例
以下是一个使用fs::path
类的详细代码示例,展示了路径的拼接、分解和规范化等操作:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
// 创建路径对象
fs::path p1("/home/user");
fs::path p2("documents/file.txt");
// 拼接路径
fs::path fullPath = p1 / p2;
std::cout << "Full path: " << fullPath.string() << std::endl;
// 分解路径
std::cout << "Parent path: " << fullPath.parent_path().string() << std::endl;
std::cout << "Filename: " << fullPath.filename().string() << std::endl;
std::cout << "Stem: " << fullPath.stem().string() << std::endl;
std::cout << "Extension: " << fullPath.extension().string() << std::endl;
// 规范化路径
fs::path normalizedPath = fullPath.lexically_normal();
std::cout << "Normalized path: " << normalizedPath.string() << std::endl;
// 检查路径类型
if (fullPath.is_absolute()) {
std::cout << "Full path is absolute." << std::endl;
} else {
std::cout << "Full path is relative." << std::endl;
}
return 0;
}
上述代码演示了如何使用fs::path
类进行路径操作,包括拼接、分解、规范化和类型检查。通过fs::path
类,可以大大简化文件路径的处理逻辑,提高代码的健壮性和可读性。