使用C++批量读取文件名
1 Linux 单级目录
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <vector>
using namespace std;
DIR* dir;
struct dirent* ptr;
vector<string> fileList;
dir = opendir("/home/lumeiqi/projects/DecodeTest/testvideo");
while((ptr = readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".") != 0 && strcmp(ptr->d_name,"..") != 0)
{
cout<<"filename"<<ptr->d_name<<endl;
fileList.push_back(ptr->d_name);
}
}
closedir(dir);
2 Linux 多级目录嵌套
读一个路径下所有的文件,不管有多少文件夹,递归一下就可以了
#include <dirent.h>
#include <iomanip>
#include <string.h>
#include <string>
void ReadFile(const std::string filePath)
{
DIR* dir = opendir(filePath.c_str());
struct dirent* ptr;
while ((ptr = readdir(dir)) != NULL) {
//if(ptr->d_name != "." && ptr->d_name != "..")
if (strcmp(ptr->d_name,".") != 0 && strcmp(ptr->d_name,"..") != 0) {
std::string subDirect = filePath;
//d_type 文件(8)、目录(4)
if (ptr->d_type == 4) {
// cout<<ptr->d_name<<endl;
subDirect += "/";
subDirect += ptr->d_name;
ReadFile(subDirect);
} else if(ptr->d_type == 8) {
// cout<<ptr->d_name<<endl;
std::string absolutePath = subDirect + "/";
absolutePath += ptr->d_name;
}
}
}
}
3 Windows 多级目录嵌套
使用