#include<stdio.h> #include<stdlib.h> #include<dirent.h> #include<string.h> #include<sys/stat.h> void printdir(char *dir,int depth) { //打开目录指针 DIR *Dp; //文件目录结构体 struct dirent *enty; //详细文件信息结构体 struct stat statbuf; //打开指定的目录,获得目录指针 if(NULL == (Dp = opendir(dir))) { fprintf(stderr,"can not open dir:%s\n",dir); return; } //切换到这个目录 chdir(dir); //遍历这个目录下的所有文件 while(NULL != (enty = readdir(Dp) )) { //通过文件名,得到详细文件信息 lstat(enty->d_name,&statbuf); //判断是不是目录 if(S_ISDIR(statbuf.st_mode)) { //当前目录和上一目录过滤掉 if(0 == strcmp(".",enty->d_name) || 0 == strcmp("..",enty->d_name)) { continue; } //输出当前目录名 printf("%*s%s/\n",depth," ",enty->d_name); //继续递归调用 printdir(enty->d_name,depth+4); } else { //输出文件名 printf("%*s%s\n",depth," ",enty->d_name); } } //切换到上一及目录 chdir(".."); //关闭文件指针 closedir(Dp); } int main(int argc,char **argv) { char *topdir = "/home/administrator/桌面/test"; if(argc > 2) { printf("it is in here\n"); topdir = argv[1]; } printf("Directory scan of %s\n",topdir); printdir(topdir,0); printf("Done\n"); exit(0); }
}