***#Linux 解析文件夹和文件C++代码
***:
一、解析文件夹代码:
void GetFileNames(string path, vector<string>& filenames)
{
DIR *pDir;
struct dirent* ptr;
if (!(pDir = opendir(path.c_str()))) {
cout << "Folder doesn't Exist!" << endl;
return;
}
while ((ptr = readdir(pDir)) != 0) {
if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
filenames.push_back(path + "/" + ptr->d_name);
}
}
closedir(pDir);
}
二、解析文件夹和文件夹下面的所有文件
vector<string> getFilesList(string dirpath) {
DIR *dir = opendir(dirpath.c_str());
if (dir == NULL)
{
cout << "opendir error" << endl;
}
vector<string> allPath;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL)
{
if (entry->d_type == DT_DIR) {//It's dir
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
string dirNew = dirpath + "/" + entry->d_name;
vector<string> tempPath = getFilesList(dirNew);
allPath.insert(allPath.end(), tempPath.begin(), tempPath.end());
}
else {
//cout << "name = " << entry->d_name << ", len = " << entry->d_reclen << ", entry->d_type = " << (int)entry->d_type << endl;
string name = entry->d_name;
string imgdir = dirpath + "/" + name;
//sprintf("%s",imgdir.c_str());
allPath.push_back(imgdir);
}
}
closedir(dir);
//system("pause");
return allPath;
}
三、获取图片的名字代码
int pos = listpath[i].find_last_of('/');
string s(listpath[i].substr(pos + 1));
char *imgp = strchr(&s[0], '.');//获取.号的位置
size_t imglen = imgp - &s[0];//长度为.号位置减去头一个字符位置
string Name = s.substr(0, imglen);//截取图名