zoukankan      html  css  js  c++  java
  • linux系统编程统计一个目录下的普通文件个数

    主要是为了统计linux系统下一个指定目录下面的普通文件个数,运用目录操作的一些函数,配合递归调用来实现该功能。

    首先介绍一下函数原型:

      打开一个空目录
                        DIR *opendir(const char *name);
                        参数: 目录名
                        返回值: 指向目录的指针
            读目录
                        struct dirent *readdir(DIR *dirp);
                        参数: opendir的返回值
                        返回值: 指向目录的指针

       关闭目录
                        int closedir(DIR *dirp);

    代码实现:readfileNum.c

     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <stdlib.h>
     4 #include <dirent.h>
     5 #include <sys/types.h>
     6 
     7 
     8 int get_file_num(char* root)
     9 {
    10     int total = 0;
    11     DIR* dir = NULL;
    12     // 打开目录
    13     dir = opendir(root);
    14     // 循环从目录中读文件
    15 
    16     char path[1024];
    17     // 定义记录目录指针
    18     struct dirent* ptr = NULL;
    19     while( (ptr = readdir(dir)) != NULL)
    20     {
    21         // 跳过. 和 ..
    22         if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
    23         {
    24             continue;
    25         }
    26         // 判断是不是目录
    27         if(ptr->d_type == DT_DIR)
    28         {
    29             sprintf(path, "%s/%s", root, ptr->d_name);
    30             // 递归读目录
    31             total += get_file_num(path);
    32         }
    33         // 如果是普通文件
    34         if(ptr->d_type == DT_REG)
    35         {
    36             total ++;
    37         }
    38     }
    39     closedir(dir);
    40     return total;
    41 }
    42 
    43 int main(int argc, char* argv[])
    44 {
    45     if(argc < 2)
    46     {
    47         printf("./a.out path");
    48         exit(1);
    49     }
    50 
    51     int total = get_file_num(argv[1]);
    52     printf("%s has regfile number: %d\n", argv[1], total);
    53     return 0;
    54 }

    效果展示:

    努力不一定有结果,有结果不一定是努力
  • 相关阅读:
    php7.4 降级 php7.1 的坑
    python 记录网页 生成pdf
    Mac 安装常用软件环境
    python 2.7 操作 excel
    007整数反转
    006Z字形变换
    005最长回文子串
    004寻找两个正序数组的中位数
    003无重复字符的最长子串
    002两数相加
  • 原文地址:https://www.cnblogs.com/liunianshiwei/p/6045395.html
Copyright © 2011-2022 走看看