/*
****************************************************************************
******文件扫描
******使用:向address变量输入要搜索的磁盘(亦或者目录地址)即可搜索目录下所有的文件(包括多层文件夹)
******如:输入 C:\\a*. 将会搜索a文件夹里所有的文件和文件夹,当a文件夹存在文件夹b,将会搜索b文件夹里所有的文件
******以此类推...
******by冬寂
*****************************************************************************
*/
#include<stdio.h>
#include<io.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#define max 10000
int main()
{
char*address[max]={"D:\\*.","E:\\*.","F:\\*."}; //搜索地址
char*names[max]; //中转地址
int i=0;
int files=0; //记录每次循环扫描address得到的文件数量
long Handle; //io.h
struct _finddata_t Fileinfo; //io.h
while(1){
while(address[i]!=NULL){
if((Handle=_findfirst(address[i],&Fileinfo))!=-1L){
char world[100];
strcpy(world,address[i]);
for(int i_world=strlen(world);i_world>0;i_world--){
//printf("[%s]\n",world);
if(world[i_world]=='\\'){
world[i_world+1]='\0';//去掉搜索后缀以便于赋值给names
break;
}
}
//printf("**********************%s:*********************\n",address[i]);
while(_findnext(Handle,&Fileinfo)==0){
if(Fileinfo.name[0]!='.'){
names[files]=(char*)malloc(strlen(world)+strlen(Fileinfo.name)+1); //申请动态内存的大小为当前文件夹位置与搜素到的文件之和
strcpy(names[files],world); //获取当前搜索的文件夹
strcat(names[files],Fileinfo.name);
//printf("%s %d\n",names[files],files);
files++;
}
}//if
_findclose(Handle);
}
i++;
}
//printf("\nfiles:%d\n\n",files);
char sanmiao[100];
strcpy(sanmiao,address[0]);
sanmiao[strlen(sanmiao)-3]='\0';
if(strcmp(sanmiao,names[0])==0) exit(0);//判断扫描是否结束
for(int j=0;j<files;j++){
if(j<i){
free(address[j]);
address[j]=NULL;
}
address[j]=(char*)malloc(strlen(names[j])+4);
strcpy(address[j],names[j]);
strcat(address[j],"\\*.");
free(names[j]);
names[j]=NULL;
long Handles;
struct _finddata_t Fileinfos;
char first_name[100];
strcpy(first_name,address[j]);
strcat(first_name,"*\0");
if((Handles=_findfirst(first_name,&Fileinfos))!=-1L){
char file_name[100];
while(_findnext(Handles,&Fileinfos)==0){
if(Fileinfos.name[0]!='.'){
strcpy(file_name,address[j]);
file_name[strlen(file_name)-2]='\0';
strcat(file_name,Fileinfos.name);
printf("%s\n",file_name);
}
}
_findclose(Handles);
}
//printf("%s %d\n",address[j],j);
}
files=0;
i=0;
}
}//main
此代码可以扫描磁盘亦可以扫描文件夹,被注释掉的printf均可作为不同输出,请自行检测。
第一篇文章可能写的不好,但是感觉有好多人在问这个问题,这里做出解决,大佬勿喷。