c语言递归法查找指定目录下的文件或目录
本代码是个人学习过程中写下的小练笔,如果您发现问题,欢迎指正。
编译环境:linux+gcc, windows下尚未测试
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<dirent.h>
#include<sys/time.h>
#include<unistd.h>
//int count;
char path[1000];
char name[100];
//struct timeval t1,t2;
void ls(char *path,char *name)
{
char apath[1000];
DIR *dir; //千万不能设为全局变量
char newpath[1000];
struct dirent *ptr;
dir=opendir(path);
if(dir!=NULL)
{
while((ptr=readdir(dir))!=NULL)
{
//printf("%s\n",ptr->d_name);
if(ptr->d_type==4&&strcmp(ptr->d_name,".")!=0&&strcmp(ptr->d_name,"..")!=0) //条件设置尽可能精确,防止误排除
{
if(strcmp(ptr->d_name,name)==0)//筛选出符合条件的目录
{
strcpy(apath,path); //绝对不能直接获取绝对路径
if(apath[strlen(apath)-1]=='/') //判断地址格式
{
strcat(apath,ptr->d_name);
}
else
{
strcat(apath,"/");
strcat(apath,ptr->d_name);
}
printf("%s\n",apath); //打印绝对地址
}
if(path[strlen(path)-1]=='/')
{
sprintf(newpath,"%s%s",path,ptr->d_name);
}
else
{
sprintf(newpath,"%s/%s",path,ptr->d_name);
}
ls(newpath,name); //递归循环
}
else if(strcmp(ptr->d_name,".")!=0&&strcmp(ptr->d_name,"..")!=0&&strcmp(ptr->d_name,name)==0) //筛选出同名文件
{
strcpy(apath,path);
if(apath[strlen(apath)-1]=='/')
{
strcat(apath,ptr->d_name);
}
else
{
sprintf(apath,"%s/%s",apath,ptr->d_name);
}
printf("%s\n",apath );
//++count;
}
}
closedir(dir);
}
else
{
//printf("Failed to open %s, need permission!\n",path);
}
}
int main(void)
{
while(1)
{
//count=0;
printf("path:"); //查找目录
scanf("%s",path); //文件名称
printf("file:");
scanf("%s",name);
//gettimeofday(&t1,NULL); //LINUX下计时,性能测试工具
ls(path,name);
//gettimeofday(&t2,NULL);
//long timeuse =1000000 * ( t2.tv_sec - t1.tv_sec ) + t2.tv_usec - t1.tv_usec;
//printf("total files %d \ntotal time %f s\n",count,timeuse/1000000.0);
}
}
|