1 #include2 #include 3 #include 4 5 #include 6 #include 7 #include 8 9 void printdir(char * dir, int depth)//这个是主要的打印目录函数,参数dir表征路径,参数depth代表缩进的空格10 {11 DIR *dp; //声明一个DIR *结构的dp12 struct dirent *entry; //声明dirent结构指针entry这个结构里面含有ino_t格式的d_ino和char格式的d_name[]13 struct stat statbuf; //声明stat格式的statbuf14 15 if((dp = opendir(dir))==NULL)//,打开目录,建立目录流,判断打开的目录不是空16 {17 fprintf(stderr,"cannot open directory:%s\n",dir);//要是空的话给标准错错误写提示18 return;19 }20 chdir(dir); //改变到传入的目录中去21 while((entry=readdir(dp))!=NULL)//读取目录流dp,获得一个指针,成功的话进入循环22 {23 lstat(entry->d_name,&statbuf);//获取指定路径(dirent结构指针)的描述到stat结构statbuf中24 if(S_ISDIR(statbuf.st_mode))//判断这个路径文件是不是目录,25 { //是目录的话进入循环26 if(strcmp(".",entry->d_name)==0||strcmp("..",entry->d_name)==0)27 continue;//如果是.或者..目录的话,继续执行28 printf("%*s%s/\n",depth," ",entry->d_name);//首先按照depth缩进,打印这个目录的文件名29 printdir(entry->d_name, depth+4);//递归调用这个函数本身,也就是进入这个目录中,缩进增加四个空格30 } //(2层)在这个函数里面只有文件,就不进入这个循环31 else32 printf("%*s%s\n",depth," ",entry->d_name);//不是目录的话,打印按照depth的缩进打印出文件名33 }34 chdir("..");//第一次循环失败的话返回上级目录(2层)打印完成之后跳出这个目录,继续上层没完成的打印35 closedir(dp);//关闭打开的流 (2层)关闭流,防止超过36 }37 int main (int argc, char * argv[])// 主函数38 {39 char * topdir="."; //定义char *类型的topdir指向当前目录也就是.40 if (argc>=2) //要是输入的参数不是空41 topdir=argv[1]; //就把要打印的路径赋值给topdir42 //argv[0]代表程序本身,要是输入的参数是空,也就是默认的打印的目录就是topdir="."43 printf("Directory scan of %s\n",topdir);//打印一句话44 printdir(topdir,0);//调用函数,实现循环打印45 printf("done.\n");46 47 exit(0);48 }
运行效果:
1 jason@t61:~/桌面$ ls 2 a.out apue.h apue.h~ printdir.c printdir.c~ 无标题文档 无标题文档~ 3 jason@t61:~/桌面$ gcc printdir.c 4 jason@t61:~/桌面$ ./a.out 5 Directory scan of . 6 printdir.c~ 7 无标题文档 8 apue.h~ 9 a.out10 printdir.c11 apue.h12 无标题文档~13 done.
参考文献:
Linux程序设计 Neil Matthew
UNIX环境高级编程 W. Richard Stevens
http://www.cnblogs.com/avril/archive/2010/03/22/1691477.html