C语言实现Linux下读取指定目录下普通文件的个数

打开一个目录

  • DIR opendir(const char name);
    • 参数: 目录名
    • 返回值: 指向目录的指针
  • FILE* fp = fopen()
  • fread(buf, len, len,fp);

读目录

1
2
3
4
5
6
7
8
struct dirent
{
ino_t d_ino; // 此目录进入点的inode
ff_t d_off; // 目录文件开头至此目录进入点的位移
signed short int d_reclen; // d_name 的长度, 不包含NULL 字符
unsigned char d_type; // d_name 所指的文件类型
har d_name[256]; // 文件名
};
  • d_type
    • DT_BLK - 块设备
    • DT_CHR - 字符设备
    • DT_DIR - 目录
    • DT_LNK - 软连接
    • DT_FIFO - 管道
    • DT_REG - 普通文件
    • DT_SOCK - 套接字
    • DT_UNKNOWN - 未知
  • struct dirent readdir(DIR dirp);
    • 参数: opendir的返回值
    • 返回值: 目录项结构体

关闭目录

  • int closedir(DIR *dirp);

独立完成递归读目录中指定类型文件个数的操作.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>

int get_file_num(char* root){
int total = 0;
DIR* dir = NULL;
// 打开目录
dir = opendir(root);
// 循环从目录中读文件

char path[1024];
// 定义记录xiang指针
struct dirent* ptr = NULL;
while( (ptr = readdir(dir)) != NULL){
// 跳过. he ..
if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0){
continue;
}
// 判断是不是目录
if(ptr->d_type == DT_DIR){
sprintf(path, "%s/%s", root, ptr->d_name);
// 递归读目录
total += get_file_num(path);
}
// 如果是普通文件
if(ptr->d_type == DT_REG){
total ++;
}
}
closedir(dir);
return total;
}

int main(int argc, char* argv[]){
if(argc < 2){
printf("./a.out path");
exit(1);
}

int total = get_file_num(argv[1]);
printf("%s has regfile number: %d\n", argv[1], total);
return 0;
}

文章结束了,但我们的故事还在继续
坚持原创技术分享,您的支持将鼓励我继续创作!