注册 登录
编程论坛 C++教室

文件列表不显示出来

chaw899 发布于 2019-06-20 21:42, 2014 次点击
#include <iostream>
#include <vector>
#include <string>
#include <dirent.h>
using namespace std;
 
void SplitString(const std::string& s, std::vector<std::string>& v, const

std::string& c)
{
  std::string::size_type pos1, pos2;
  pos2 = s.find(c);
  pos1 = 0;
  while(std::string::npos != pos2)
  {
    v.push_back(s.substr(pos1, pos2-pos1));
 
    pos1 = pos2 + c.size();
    pos2 = s.find(c, pos1);
  }
  if(pos1 != s.length())
    v.push_back(s.substr(pos1));
}
 
void readFileList(string path, vector<string> &files, string ext){
    struct dirent *ptr;
    DIR *dir;
    dir=opendir(path.c_str());
    while((ptr=readdir(dir))!=NULL)
    {
        if(ptr->d_name[0] == '.')
            continue;
        std::vector<std::string> strVec;
        SplitString(ptr->d_name, strVec, ".");
 
        if(strVec.size() >=2)
        {
            string p;
            if(strVec[strVec.size()-1].compare(ext) == 0)
                files.push_back(p.assign(path).append("/").append(ptr->d_name));
        }
        else{
            string p;
            readFileList(p.assign(path).append("/").append(ptr->d_name), files,

ext);
        }
    }
    closedir(dir);
}
 
int main(int argc, char * argv[])
{
    string PATH = "I:/185";
    vector<string> files;
    readFileList(PATH, files, "tu.*");  // 本意想显示tu开头的的文件列表没有显示
    readFileList(PATH, files, "png");   // 这句可以显示扩展名png的列表
    for (int i = 0; i < files.size(); ++i)
    {
        cout << files[i] << endl;
    }
    return 0;
}

3 回复
#2
rjsp2019-06-21 09:05
if(strVec[strVec.size()-1].compare(ext) == 0)
这是要求文件扩展名必须是“tu.*”才行呀
代码抄的吧,抄完了也没看一样吧
#3
chaw8992019-06-21 14:50
回复 2楼 rjsp
怎么写才能支持通佩符呢
#4
rjsp2019-06-21 15:10
回复 3楼 chaw899
linux 用 fnmatch
windows 用 PathMatchSpec
1