一个linux目录扫描程序

 1 #include <unistd.h>
 2 #include <stdio.h>
 3 #include <dirent.h>
 4 
 5 #include <string.h>
 6 #include <sys/stat.h>
 7 #include <stdlib.h>
 8 
 9 void printdir(char * dir, int depth)//这个是主要的打印目录函数,参数dir表征路径,参数depth代表缩进的空格
10 {
11     DIR *dp;                    //声明一个DIR *结构的dp
12     struct dirent *entry;  //声明dirent结构指针entry这个结构里面含有ino_t格式的d_ino和char格式的d_name[]
13     struct stat statbuf;            //声明stat格式的statbuf
14     
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         else
32         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];        //就把要打印的路径赋值给topdir
42                   //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.out
10  printdir.c
11  apue.h
12  无标题文档~
13 done.

参考文献:

Linux程序设计 Neil Matthew

UNIX环境高级编程 W. Richard Stevens

http://www.cnblogs.com/avril/archive/2010/03/22/1691477.html

原文地址:https://www.cnblogs.com/kongchung/p/4601566.html