#include <stdio.h>
#include <vector>
#include "stdlib.h"
#include "stdio.h"
#include <string>
#include <iostream>
#include <io.h>
using namespace std;
static auto cutNext(string stream, const string &str) {
int nPos = stream.find(str);
if (nPos != -1) {
stream = stream.substr(nPos + str.size(), stream.size());
}
return stream;
}
static auto cutPre(string stream, const string &str) {
int nPos = stream.find(str);
if (nPos != -1) {
stream = stream.substr(0, nPos);
}
return stream;
}
void getAllFiles(string path, vector<string>& files, string format)
{
intptr_t hFile = 0;//文件句柄
struct _finddata_t fileinfo;//文件信息
string p;
//if ((hFile = _findfirst(p.assign(path).append("/*" + format).c_str(), &fileinfo)) != -1) //文件存在
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(p.assign(path).append("/").append(fileinfo.name)); //保存文件夹名
getAllFiles(p.assign(path).append("/").append(fileinfo.name), files, format); //递归遍历文件夹
}
}
else
{
string x;
x="."+cutNext(p.assign(path).append("/").append(fileinfo.name),".");
if (format==x)
files.push_back(p.assign(path).append("/").append(fileinfo.name));//如果不是文件夹,储存文件名
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
int main()
{
string filePath = "路径(不要有多余的'.')";
string format = ".txt"; //查找文件的格式
vector<string> files;
getAllFiles(filePath, files, format);
int filessize = files.size();
for (int i = 0; i < filessize; i++)
{
cout<<files[i].c_str()<<endl;
}
}
|