// Walking.cpp : 定义控制台应用程序的入口点。
//
#include <string>
#include <vector>
#include <regex>
#ifdef _MSC_VER
#define DIR_CHAR "\\"
#include<io.h>
#else
#define DIR_CHAR "/"
#include <stdio.h>
#include <dirent.h>
#endif
using namespace std;
#ifdef _MSC_VER //windows和linux获取文件列表方法不同
//递归获取所有文件夹下文件
void Walking(string sInputDir, vector<string>& sFileList,string sSuffix)
{
string tmp = "\\*";
//文件句柄
long hFile = 0;
//文件信息
struct _finddata_t fileinfo; //很少用的文件信息读取结构
string p; //string类很有意思的一个赋值函数:assign(),有很多重载版本
if ((hFile = _findfirst(p.assign(sInputDir).append(tmp).c_str(), &fileinfo)) != -1)
{
do
{
if (strcmp(fileinfo.name, ".") == 0 || strcmp(fileinfo.name, "..") == 0)
continue;
if (fileinfo.attrib & _A_SUBDIR) //判断是否为文件夹
{
string sTmpDir = p.assign(sInputDir).append(DIR_CHAR).append(fileinfo.name);
Walking(sTmpDir,sFileList,sSuffix);
}
else if(!(fileinfo.attrib & _A_SUBDIR)) //文件处理
{
string sFileName = sInputDir + string(DIR_CHAR) +string(fileinfo.name);
printf("%s\n",sFileName.c_str());
//正则表达式判断
if (1==0)
{
sFileList.push_back(sFileName);//文件名
}
}
} while (_findnext(hFile, &fileinfo) == 0); //寻找下一个,成功返回0,否则-1
_findclose(hFile);
}
}
#else
void Walking(string sInputDir, vector<BaseFileName>& sFileList,string sSuffix)
{
int nLength = sSuffix.length();//suffix为空时,获取文件夹列表,非空时获取固定格式文件
DIR *pDir = NULL;
struct dirent *entry;
pDir=opendir(sInputDir.c_str());
if (pDir==NULL)
{
return;
}
while((entry=readdir(pDir))!=NULL)
{
if(strcmp(entry->d_name,".")==0||strcmp(entry->d_name,"..")==0)
continue;
if((entry->d_type&DT_DIR)&&nLength==0)
{
string tmppath = sInputDir +string(DIR_CHAR)+ string(entry->d_name);
BaseFileName filename;
filename.sFileName = tmppath;
sFileList.push_back(filename);//保存文件夹名字
Walking(tmppath,sFileList,sSuffix);
}
else if(!(entry->d_type&DT_DIR)&&nLength>0)
{
BaseFileName filename;
filename.sFileName = entry->d_name;
if (SuffixMatch(filename,sSuffix)==0)
{
sFileList.push_back(filename);//文件名
}
}
else
;
}
closedir(pDir);
}
#endif
int main(int argc, char * argv[])
{
char *cInputDir = "D:\\VMcentosShare\\DATAROOT\\STDPRODUCT\\HY-1C";
vector<string> vFileList;
string pattern = "^H1C_ERTP_OCT_L2D_\\d{8}T\\d{6}_\\d{8}T\\d{6}_\\d{5}_10.h5$" ; // fixed telephone
regex re(pattern);
vector<string> str;
str.push_back("H1C_ERTP_OCT_L2D_20190226T112911_20190226T113000_02479_10.h5");
str.push_back("H1C_ERTP_OCT_L2D_20190226T112911_20190226T113000_02479_10.meta.xml");
str.push_back("H1C_ERTP_OCT_L2D_20190226T112911_20190226T113000_02479_10.h5.jpg");
for (vector<string>::iterator it = str.begin();it!=str.end();it++)
{
string &tmp = (*it);
bool ret = regex_match(tmp, re);
if (ret)
fprintf(stderr, "%s, can match\n", tmp.c_str());
else
fprintf(stderr, "%s, can not match\n", tmp.c_str());
}
string sRe = "";
Walking(cInputDir,vFileList,sRe);
return 0;
}
c++遍历文件+正则表达式筛选文件
最新推荐文章于 2022-09-07 17:27:19 发布