本博实现遍历指定目录下的所有文件(夹),以及输出指定类型的文件
代码如下:
#include <iostream>
#include <io.h>
#include <string>
using namespace std;
//遍历该目录下的所有文件(夹)
void dir(string path)
{
long hFile = 0;
struct _finddata_t fileInfo;
string pathName, excName;
// \\*代表要遍历所有的类型
if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -1)
{
return;
}
do
{
//判断文件的属性是文件夹还是文件
cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR ? "[folder]" : "[file]") << endl;
} while (_findnext(hFile,&fileInfo)==0);
_findclose(hFile);
return;
}
//遍历该目录下的.txt文件
void dir_custom(string path, string type)
{
long hFile = 0; //句柄
struct _finddata_t fileInfo;
string pathName;
if ((hFile = _findfirst(pathName.assign(path).append("\\*.*").c_str(), &fileInfo)) == -1)
{
return;
}
do
{
const char* s = fileInfo.name;
const char* t = type.data();
if (fileInfo.attrib&_A_SUBDIR) //是子文件夹
{
cout << "[Folder]:" <<fileInfo.name << endl;
//遍历子文件夹中的文件(夹),查看是否有txt文件
if(strcmp(s,".")==0 || strcmp(s,"..")==0) //子文件夹目录是.或者..
continue;
string sub_path = path + "\\" + fileInfo.name;
cout << sub_path << endl;
dir_custom(sub_path, type);
}
else //判断是不是txt文件
{
if (strstr(s,t))
{
cout << fileInfo.name << "\t" << path << "\t" << fileInfo.size << " bytes.\n";
}
}
} while (_findnext(hFile,&fileInfo)==0);
return;
}
int main()
{
//给定目录
string path = "G:\\test";
//遍历该目录下的所有文件(夹)
dir(path);
cout << endl << endl;
//输出该目录下的所有type类型的文件
string type = ".txt";
dir_custom(path, type);
system("pause");
return 0;
}
运行效果,感觉有点慢- -:
然后我实际上是创建了一个test文件夹:
参考博客:
https://blog.csdn.net/abcjennifer/article/details/18147551
https://www.cnblogs.com/Pillar/p/4206452.html
https://blog.csdn.net/sinat_31771313/article/details/79207105
https://blog.csdn.net/a342500329a/article/details/83855774