博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一个linux目录扫描程序
阅读量:7250 次
发布时间:2019-06-29

本文共 2020 字,大约阅读时间需要 6 分钟。

1 #include 
2 #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

转载于:https://www.cnblogs.com/kongchung/p/4601566.html

你可能感兴趣的文章
命好不如习惯好
查看>>
/etc/X11/xorg.conf 文件被误改后进不了图形化界面
查看>>
Android 通过反射及AIDL获取双卡手机SIM卡相关信息,及注册监听
查看>>
shell批量新建文件及批量改名
查看>>
APP适配安卓手机刘海屏
查看>>
bind10 新版本发布(版本号bind10-devel-20120816)
查看>>
junit 参数化测试
查看>>
分区表维护
查看>>
听说iPhone X到货了,识别体验是不是科技感爆棚?
查看>>
windows server2012中创建密码重设盘
查看>>
openstack-icehouse部署中遇到的一些故障(小笔记)
查看>>
redhat 替换 yum
查看>>
Google决定用gLinux取代Goobuntu Linux操作系统
查看>>
《将博客搬至CSDN》
查看>>
TCP/IP和OSI参考模型
查看>>
python日志管理模块logging
查看>>
Android用Intent和Bundle传list
查看>>
MySQL count(*) 优化
查看>>
西城110/linux高级作业(12.26)
查看>>
负载产品性能测试——新建测试
查看>>