std::filesystem是C++17中引入的一个标准库,用于操作文件系统。它提供了一组跨平台的API,可以方便地进行文件和目录的操作,如创建、删除、重命名、移动等。
std::filesystem API与POSIX API相比具有更简洁、更易用的接口,同时也支持更多的特性,如文件属性查询、访问控制、文件内容读取等。
使用std::filesystem需要包含头文件,并在编译时指定C++17或更高版本的标准。
在C++中,可以使用标准库中的头文件<filesystem>来操作文件系统。具体实现如下:
#include <iostream>
#include <filesystem>
#include <string>
void find_files(const std::string& path, const std::string& ext) {
for (const auto& entry : std::filesystem::directory_iterator(path)) {
if (entry.is_regular_file() && entry.path().extension() == ext) {
std::cout << entry.path() << std::endl;
}
}
}
int main() {
std::string path = "D:/xxx/LocalTest/CameraImages/a";
std::string ext = ".bmp";
find_files(path, ext);
return 0;
}
其中,find_files函数接收两个参数,分别是目录路径和扩展名。使用std::filesystem::directory_iterator遍历目录下的所有文件和子目录,判断是否为普通文件并且扩展名是否符合要求,如果符合则输出文件路径。最后在main函数中调用find_files函数即可。