std::filesystem 是 C++17 标准引入的文件系统库,提供了一套用于处理文件和目录的 API。它主要包括以下几个核心类:
std::filesystem::path
:用于表示文件系统路径。它提供了一系列方法,允许你对路径进行各种操作,如拼接、分解、获取文件名等。路径可以是相对路径或绝对路径,可以包含文件名、目录名等信息。std::filesystem::directory_entry
:用于表示目录中的一个条目,可以是文件或目录。你可以使用这个类来检查目录中的条目类型、获取条目路径等信息。std::filesystem::directory_iterator
:是一个用于遍历目录内容的迭代器。你可以使用它来遍历目录中的所有文件和子目录,并获取它们的信息。std::filesystem::create_directory
:用于创建目录std::filesystem::remove
:用于删除文件或目录
一些常用功能示例
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
// 运行时修改工作目录为当前工作目录的上一级目录
fs::current_path("../");
// 获取当前项目的工作目录
fs::path currentPath = fs::current_path();
std::cout << currentPath << std::endl;
// 构造路径
fs::path filePath = currentPath / "example" / "test.txt";
// 获取路径信息
std::cout << "Current Path: " << currentPath << std::endl;
std::cout << "File Path: " << filePath << std::endl;
std::cout << "File Name: " << filePath.filename() << std::endl;
std::cout << "Parent Path: " << filePath.parent_path() << std::endl;
std::cout << "Root Path: " << filePath.root_path() << std::endl;
std::cout << "Extension: " << filePath.extension() << std::endl;
// 连接路径
fs::path subdir = "subdirectory";
fs::path combinedPath = filePath.parent_path() / subdir / filePath.filename();
std::cout << "Combined Path: " << combinedPath << std::endl;
// 迭代目录下该目录下所有文件的路径
std::cout << "Contents of current directory:" << std::endl;
for (const auto& entry : fs::directory_iterator(currentPath))
{
std::cout << entry.path() << std::endl;
}
// 检查路径是否存在
std::cout << "File exists: " << fs::exists(filePath) << std::endl;
// 文件更名
fs::rename(filePath, filePath.parent_path() / "ttttt.txt");
std::cout << "File Path: " << filePath << std::endl;
return 0;
}
关于项目当前工作目录(working directory)
- (1)如果是在IDE中构建-运行,则工作目录默认是$(projectDir)即项目根目录(在项目属性中修改)
- (2)如果是双击.exe可执行文件直接运行,则工作目录会是.exe所在路径
如果用代码动态修改了项目工作目录(比如修改为…/),则也要看运行方式是什么,
- 如果是(1),则工作目录变为
$(projectDir)
的上级目录 - 如果是(2),则为.exe所在目录的上级目录