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 }

      运行结果:

      

  • 相关阅读:
    Windows下PATH等环境变量详解
    html表单,做个申请邮箱界面练习。
    截取字符串,去空格的练习。
    for循环
    c# if else的练习,判断闰年,输入日期,输出这是今年的的多少天!
    HTML
    输入输出2
    输入输出练习1
    Map练习
    数据库设计范式
  • 原文地址:https://www.cnblogs.com/general0878/p/7214244.html
Copyright © 2011-2022 走看看