#pragma warning(disable:4996);
#include <stdio.h>
#include < io.h >
#include<cstdbool>
#include<string.h>
/*
查询路径下所有指定格式文件
path:路径 例:C:\\Users\\FUHUAEI\\Documents\\lib\\
file_num:查到文件数
recursion:是否递归查询
type:查询类型 .* .MP3 .txt
return:成功查询
*/
bool TraverseFiles_name(const char* path, int file_num, bool recursion, const char* type)
{
//路径组合
char current_path[sizeof(path) + 128];
sprintf(current_path, "%s*.*", path );//路径加*.*查询文件夹下所有文件夹及文件
_finddata_t fileinfo;
intptr_t handle = _findfirst(current_path, &fileinfo);//打开文件查找句柄
if (handle == -1)
return false;
do
{
//.是当前目录,..是上层目录,必须排除掉这两种情况
if (strcmp(fileinfo.name, "..") == 0 || strcmp(fileinfo.name, ".") == 0)
{
continue;
}
//判断是否是目录
if (fileinfo.attrib == _A_SUBDIR) //是目录
{
if (recursion == true)//是否递归查询
{
char path_1[sizeof(path) + 128];
strcpy(path_1, path);
sprintf(path_1, "%s%s\\", path, fileinfo.name);
printf("path_1 = %s\n", path_1); //文件名(带后缀)
TraverseFiles_name(path_1, file_num, false, type);
}
}
else//是文件
{
if(strstr(fileinfo.name, type)!=NULL)
{
char path_2[sizeof(path) + 128];
printf("filename = %s\n", fileinfo.name); //文件名(带后缀)
sprintf(path_2, "%s%s", path, fileinfo.name);//文件名(带后缀及路径)
printf("filename = %s\n", path_2); //文件名(带后缀及路径)
//此处做手脚保存文件名可以传个file什么的
}
}
//printf("filename = %s\n", fileinfo.name); //文件名(带后缀)
//printf("%d\n", fileinfo.time_write); //文件最后修改时间
//printf("size = %d\n", fileinfo.size); //文件字节数(文件夹显示0)
//printf("%s\n", attribute); //文件是否目录
file_num++; //计数
} while (!_findnext(handle, &fileinfo)); //返回0则遍历完
//关闭文件句柄
_findclose(handle);
return true;
}
int main()
{
TraverseFiles_name("C:\\Users\\FUHUAEI\\Documents\\ii\\", 0,false, ".txt");
return 0;
}