• 得到一个简单的子目录内容清单


           要求:得到一个简单的子目录内容清单。子目录中的每一个文件单独列在一行上。如果是一个下级子目录,在它的名字后面加一个斜线字符“/”。下级子目录中的文件在缩进4个空格后一次排列。

    1. 打开子目录创建一个子目录流,并判断该目录是否存在。
    2. 进入该目录
    3. While该目录不为空 do

    1)  将文件的状态信息取到一个结构体中

    2)  判断该文件是否为目录

           是:a、判断是否是“.”或“..”目录

                 是:回到while循环

                 否:打印子目录名等,然后进行递归调用

          否:打印文件名

        4.退出该目录

        5.关闭子目录流

     1 /*
     2  ============================================================================
     3  Name        : GetDirInfo.c
     4  Author      : 
     5  Version     :
     6  Copyright   : Your copyright notice
     7  Description : Hello World in C, Ansi-style
     8  ============================================================================
     9  */
    10 
    11 #include <unistd.h>
    12 #include <stdio.h>
    13 #include <dirent.h>
    14 #include <string.h>
    15 #include <sys/stat.h>
    16 #include <stdlib.h>
    17 
    18 int main() {
    19     printf("Directory scan of /home/fjnucse:\n");
    20     printdir("/home/fjnucse", 0);
    21     printf("done.\n");
    22 
    23     exit(0);
    24 }
    25 
    26 void printdir(char * dir, int depth) {
    27     DIR * dp; //子目录处理操作
    28     struct dirent *entry; //目录数据项
    29     struct stat statbuf; //通过文件名查到的状态信息
    30 
    31     if ((dp = opendir(dir)) == NULL) //打开目录
    32     {
    33         fprintf(stderr, "cannot open direntory:%s\n", dir);
    34         return;
    35     }
    36 
    37     chdir(dir); //创建子目录流
    38 
    39     while ((entry = readdir(dp)) != NULL)
    40     //读目录
    41     {
    42         lstat(entry->d_name, &statbuf); //通过文件名查到的状态信息
    43 
    44         if (S_ISDIR(statbuf.st_mode)) //文件权限和文件类型信息
    45         {
    46             if (strcmp(".", entry->d_name) == 0
    47                     || strcmp("..", entry->d_name) == 0) {
    48                 continue;
    49             }
    50 
    51             printf("%*s%s/\n", depth, "", entry->d_name);
    52             printdir(entry->d_name, depth + 4);
    53         } else {
    54             printf("%*s%s/\n", depth, "", entry->d_name);
    55         }
    56     }
    57 
    58     chdir(".."); //关闭子目录流
    59     closedir(dp); //退出该目录
    60 }


    作者:kissazi2
    出处:http://www.cnblogs.com/kissazi2/
    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    Cannot initialize Cluster. Please check your configuration for mapreduce.framework.name
    docker-compose 安装solr+ikanalyzer
    centos 安装Python3
    spring+springmvc+mybatis 开发JAVA单体应用
    职责链模式例子
    ssm(spring、springmvc、mybatis)框架整合
    PAT (Advanced Level) Practise
    PAT (Advanced Level) Practise
    PAT (Advanced Level) Practise
    PAT (Advanced Level) Practise
  • 原文地址:https://www.cnblogs.com/kissazi2/p/2868041.html
Copyright © 2020-2023  润新知