如何获取指定路径下全部文件夹名称
- 获取文件名称
- 正则表达式筛选
- 输出为文件txt格式
#include<iostream>
#include<vector>
#include <regex>
#include<io.h>
#include<fstream>
using namespace std;
void getSubdirs(string path, vector<string>& files);
int main()
{
string format("^[a-z]{2}[0-9]{3}");
string filePath("E:\s");
vector<string> filenames;
vector<string> results;
ofstream outFile;
outFile.open("E:/results.txt");
getSubdirs(filePath, filenames);
regex r(format);
for (int i = 0; i < filenames.size(); i++) {
cout << "目前匹配:" << filenames[i] << endl;
outFile << "目前匹配:" << filenames[i] << endl;
if (regex_match(filenames[i], r)) {
cout << "success" << endl;
outFile << "success" << endl;
results.push_back(filenames[i]);
}
else {
cout << "fail" << endl;
outFile << "fail" << endl;
}
}
cout << "筛选结果如下:" << endl;
outFile << "筛选结果如下:" << endl;
cout << "文件夹总数:" << filenames.size() << ",符合要求的数量:" << results.size() << endl;
outFile << "文件夹总数:" << filenames.size() << ",符合要求的数量:" << results.size() << endl;
for (int i = 0; i < results.size(); i++) {
cout << i + 1 << ":" << results[i] << endl;
outFile << i + 1 << ":" << results[i] << endl;
}
outFile.close();
return 0;
}
void getSubdirs(string path, vector<string>& files)
{
long long hFile = 0;
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("/*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
files.push_back(fileinfo.name);
}
else
{
;
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}