<filesystem>头文件自 C++17 起引入,提供了方便的路径操作功能
目录
3. std::filesystem::create_directory
8. std::filesystem::current_path
10. std::filesystem::canonical
11. std::filesystem::temp_directory_path
1. std::filesystem::path
std::filesystem::path
类用于表示文件系统路径,并提供多种操作路径的方法
(1) 构造函数
std::filesystem::path p("/path/to/file");
(2) 成员函数
string()
: 将路径转换为std::string
。filename()
: 获取文件名部分。parent_path()
: 获取父路径。extension()
: 获取文件扩展名。replace_extension(const path& new_extension)
: 替换文件扩展名。root_name()
: 获取根名。root_directory()
: 获取根目录。relative_path()
: 获取相对路径。is_absolute()
: 检查路径是否是绝对路径。is_relative()
: 检查路径是否是相对路径。
(3) 示例
std::filesystem::path p("/path/to/file.txt");
std::cout << p.filename() << std::endl; // 输出: file.txt
std::cout << p.parent_path() << std::endl; // 输出: /path/to
std::cout << p.extension() << std::endl; // 输出: .txt
2. std::filesystem::exists
检查文件或目录是否存在。
bool exists = std::filesystem::exists("/path/to/file");
3. std::filesystem::create_directory
创建目录。
bool success = std::filesystem::create_directory("/path/to/new_directory");
4. std::filesystem::remove
删除文件或空目录。
bool success = std::filesystem::remove("/path/to/file_or_directory");
5. std::filesystem::rename
重命名文件或目录
std::filesystem::rename("/path/to/old_name", "/path/to/new_name");
6. std::filesystem::copy
复制文件或目录。
std::filesystem::copy("/path/to/source", "/path/to/destination");
7. std::filesystem::space
获取磁盘空间信息。
std::filesystem::space_info info = std::filesystem::space("/path/to/directory");
std::cout << "Available: " << info.available << std::endl;
std::cout << "Free: " << info.free << std::endl;
std::cout << "Capacity: " << info.capacity << std::endl;
8. std::filesystem::current_path
获取或设置当前工作目录
获取:
std::filesystem::path current = std::filesystem::current_path();
设置:
std::filesystem::current_path("/new/current/directory");
9. std::filesystem::absolute
获取绝对路径
std::filesystem::path abs_path = std::filesystem::absolute("relative/path/to/file");
10. std::filesystem::canonical
获取规范路径(消除符号链接和冗余的 .
和 ..
)。
std::filesystem::path can_path = std::filesystem::canonical("/path/to/file");
11. std::filesystem::temp_directory_path
获取临时目录路径。
std::filesystem::path temp_path = std::filesystem::temp_directory_path();