前言
Linux版本需要用c++读取指定目录下的图片文件的路径。第一次编写出只包含当前目录下的图片文件,并不满足需求。然后重新编写后子目录的文件图片也可以满足。
提示:以下是本篇文章正文内容,下面案例可供参考
一、Ubuntu下c++读取指定目录及子目录下所有的图片类型文件路径或名字
1.代码
代码如下(示例):
#include <string.h>
#include <dirent.h>
#include<iostream>
#include <string>
#include <vector>
using namespace std;
int readFileList(string basePath,vector<string> &files)
{
DIR *dir;
struct dirent *ptr;
if ((dir=opendir(basePath.c_str())) == NULL)
{
perror("Open dir error...");
exit(1);
}
while ((ptr=readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///current dir OR parrent dir
continue;
else if(ptr->d_type == 8) ///file
{
string a = ptr->d_name;
int pe = a.find_last_of(".");
string pic_name = a.substr(pe + 1);
if (pic_name=="jpg") //若想获取其他类型文件只需修改jpg为对应后缀
{
string tmpname = basePath + "/" + ptr->d_name;
files.push_back(tmpname);
//name.push_back(ptr->d_name)
}
}
else if(ptr->d_type == 4) ///dir
{
string base = basePath + "/" + ptr->d_name;
readFileList(base,files);
}
}
closedir(dir);
return 1;
}
int main()
{
vector<string> temp;//文件路径
//vector<string> name;//若要只获取文件名称 修改为 readFileList("/home/yao/codes/imgtest", temp,name);
readFileList("/home/yao/codes/imgtest", temp);
for (int i = 0; i<temp.size(); i++) {
cout << temp[i] << endl;
//cout << name[i] << endl;
}
return 0;
}