红联Linux门户
Linux帮助

linux(c)广度优先遍历指定目录

发布时间:2016-10-30 09:40:45来源:linux网站作者:sdgl
// 广度优先遍历采取的是先遍历完本层目录下的所有文件和目录,当判断是目录时则将该目录加入到目录队列中,等待递归遍历这个目录
 
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <dirent.h>
#include <sys/stat.h>
char path[100000][250]={""};
int main(int argc,char *argv[])
{
fun(argv[1]);
return 0;
}
void fun(char *lname)
{
int i=0,k=1;
DIR *dir_ptr;
struct stat infobuf;
struct dirent *direntp;
char *name,temp[100]={0};
strcpy(path[0],lname);
while((strcmp(path[i],"")!=0))
{
if ((dir_ptr = opendir(path[i])) == NULL)
perror("can not open");
else
{
while ((direntp = readdir(dir_ptr))!= NULL)
{
strcpy(temp,"");
name=direntp->d_name;
if((strcmp(name,".")==0) | (strcmp(name,"..")==0))
{
printf(name);
printf("\n");
}
else
{
strcat(temp,path[i]);
strcat(temp,"/");
strcat(temp,name);
if((stat(temp,&infobuf))==-1)
printf("#########%s\n",temp);
if ((infobuf.st_mode & 0170000) == 0040000)
{
printf(name);
printf("this is a directory\n");
strcpy(path[k],temp);
k++;
}
else
{
printf(name);
printf("this is a file\n");
}
}
}closedir(dir_ptr);
}
i++;
printf(path[i]);
printf("\n********
%d\n",i);
}
}
 
本文永久更新地址:http://www.linuxdiyf.com/linux/25528.html