// Linux下递归遍历指定目录,但是因为是深度优先遍历,如果目录过多,会因为资源不足而停止,最好是采用广度优先遍历指定目录下的所有目录和文件
// 遍历时首先得过滤 .和 ..目录,有可能陷入死循环,一个表示当前目录,一个表示上一级目录。
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <dirent.h>
#include <sys/stat.h>
int main(int argc,char *argv[])
{
fun(argv[1]);
return 0;
}
void fun(char *lname)
{
DIR *dir_ptr;
struct stat infobuf;
struct dirent *direntp;
char *name,temp[100]={0};
if ((dir_ptr = opendir(lname)) == 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,lname);
strcat(temp,"/");
strcat(temp,name);
if((stat(temp,&infobuf))==-1)
printf("#########\n");
if ((infobuf.st_mode & 0170000) == 0040000)
{
printf(name);
printf(" this is a directory\n");
fun(temp);
}
else
{
printf(name);
printf(" this is a file\n");
}
}
}
}close(dir_ptr);
}
本文永久更新地址://m.ajphoenix.com/linux/25527.html