zoukankan      html  css  js  c++  java
  • linux 下的文件目录操作之遍历目录

      通过递归调用读取目录和文件信息去遍历整个目录:

      示例代码:

     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 
     8 
     9 void printdir(char * dir, int depth)
    10 {
    11     DIR * dp = opendir(dir);
    12     if (NULL == dp)
    13     {
    14         fprintf(stderr, "cannot open directory: %s
    ", dir);
    15         return;
    16     }
    17     chdir(dir);
    18     struct dirent * entry;
    19     struct stat statbuf;
    20     while ((entry = readdir(dp)) != NULL)
    21     {
    22         stat(entry->d_name, &statbuf);
    23         if (S_ISDIR(statbuf.st_mode))
    24         {
    25             if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
    26                 continue;
    27             printf("%*s%s/
    ", depth, "", entry->d_name);
    28             printdir(entry->d_name, depth + 4);
    29         }
    30         else
    31             printf("%*s%s
    ", depth, "", entry->d_name);
    32         //printf("%*s",4,"*"); 该函数表示输出"___*",前面输出3个空格。
    33         //如果是printf("%*s",4,"**");则表示输出"__**",前面输出2个空格。
    34     }
    35     chdir("..");
    36     closedir(dp);
    37 }
    38 
    39 int main(int argc, char * argv[])
    40 {
    41     char * topdir, pwd[2] = ".";
    42     if (argc < 2)
    43         topdir = pwd;
    44     else
    45         topdir = argv[1];
    46     printf("Directory scan of %s
    ", topdir);
    47     printdir(topdir, 0);
    48     printf("done.
    ");
    49     exit(0);
    50 }

      运行结果:

      

  • 相关阅读:
    jQuery 文本框得失焦点应用
    .NET 学习书籍推荐
    Android开发常见问题小结
    如何使用别人项目源码
    Android相关学习资料整理
    Android网络文件下载模块整理
    父类方法扩展
    继承后构造函数的关系
    私有属性和私有方法l
    面向对象
  • 原文地址:https://www.cnblogs.com/general0878/p/7214244.html
Copyright © 2011-2022 走看看