目录扫描printfdir

  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <dirent.h>

  4. #include <string.h>
  5. #include <sys/stat.h>
  6. #include <stdlib.h>

  7. void printdir(char *dir, int depth){
  8. DIR *dp; //DIR 结构包含在dirent.h里头
  9. struct dirent *entry;
  10. struct stat statbuf;

  11. if((dp = opendir(dir)) == NULL){
  12. //opendir打开dir参数所指向的目录并建立一个目录流,成功则返回一个指向DIR结构的指针
  13. fprintf(stderr, "cannot open directory: %s\n", dir);
  14. //失败则向标准错误流写入错误信息
  15. return;
  16. }
  17. chdir(dir);//切换目录
  18. while((entry = readdir(dp)) != NULL) {
  19. //readdir函数将返回一个指向dirent结构体的指针
  20. //dirent结构中包含文件的inode节点号(ino_t d_ino)以及文件的名字(char d_name[])
  21. lstat(entry->d_name, &statbuf);
  22. //lstat函数将文件状态信息放到参数statbuf里头
  23. if(S_ISDIR(statbuf.st_mode)) {
  24. if(strcmp(".",entry->d_name) == 0 ||
  25. strcmp("..",entry->d_name) == 0)
  26. continue;
  27. printf("%*s%s/\n",depth,"",entry->d_name);
  28. printdir(entry->d_name,depth+4);
  29. }
  30. else printf("%*s%s\n",depth,"",entry->d_name);
  31. }
  32. chdir("..");
  33. closedir(dp);
  34. }

  35. int main(){
  36. printf("Directory scan of /home:\n");
  37. printdir("/home",0);
  38. printf("done.\n");

  39. exit(0);
  40. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值