在编程世界中,目录操作是不可或缺的一部分。无论你开发什么
你都需要与文件系统(Filesystem)进行交互。C++ Filesystem库提供了一种标准化和跨平台的方式来进行这些操作。
一、如何创建目录
| create_directories | 支持创建多级目录 |
|---|---|
| create_directory | 只能创建一个 |
#include <iostream>
using namespace std;
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::create_directories("D:\\temp\\ty\\aa");//支持创建多级目录
fs::create_directory("D:\\temp1");//只能创建一个
system("pause");
return 0;
}
获取当前工作目录:
#include <iostream>
using namespace std;
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
std::filesystem::path currentPath = std::filesystem::current_path();
std::cout << "Current working directory is: " << currentPath << std::endl;
system("pause");
return 0;
}
结果:

如何遍历目录:
头文件提供了一些函数来遍历目录中的文件和子目录。可以使用directory_iterator类来遍历目录中
#include <iostream>
using namespace std;
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::path mypath = "D:\\VC++笔记\\2024";
for (auto& entry : fs::directory_iterator(mypath)) {
std::cout << entry.path() << std::endl;
}
system("pause");
return 0;
}
结果:

如果你只想遍历目录中的文件,可以使用is_regular_file()函数来判断一个条目是否是一个普通文件:
#include <iostream>
using namespace std;
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::path mypath = "D:\\VC++笔记\\2024";
for (auto& entry : fs::directory_iterator(mypath)) {
if (fs::is_regular_file(entry)) {
std::cout << entry.path() << std::endl;
}
}
system("pause");
return 0;
}

递归遍历所有文件
void FindTreeFile(std::string path)
{
for (auto& v : fs::recursive_directory_iterator(path))
{
if (fs::is_regular_file(v.path()))
{
std::cout << v.path() << std::endl;
//std::string filename = v.path().filename().string();
// std::cout << filename << std::endl;
//std::string extension_name = v.path().extension().string();
//std::cout << extension_name << std::endl;
}
}
}
另外还有拷贝,移除操作
fs::copy("source.txt", "destination.txt");
fs::remove("ty.txt");
二、path类
path:D:\temp\ty\aa\file.txt
| 方法 | 功能描述 | 示例 |
|---|---|---|
| parent_path() | 获取父路径 | D:\temp\ty\aa |
| filename() | 获取文件名 | file.txt |
| extension() | 获取文件扩展名 | .txt |
| stem() | 获取不带扩展名的文件名 | file |
#include <iostream>
using namespace std;
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::path p = "D:\\temp\\ty\\aa\\file.txt";
std::cout << "Parent path: " << p.parent_path() << std::endl; // 输出:D:\\temp\\ty\\aa
std::cout << "Filename: " << p.filename() << std::endl; // 输出:file.txt
std::cout << "stem: " << p.stem() << std::endl; // 输出:file
std::cout << "extension: " << p.extension() << std::endl; // 输出:.txt
system("pause");
return 0;
}
结果:

路径拼接:
#include <iostream>
using namespace std;
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::path p1 = "C:/Users/";
fs::path p2 = "Ty/Documents/";
fs::path p3 = p1 / p2;
std::cout << p3 << std::endl;
system("pause");
return 0;
}
结果:


5846

被折叠的 条评论
为什么被折叠?



