linux

如何用readdir获取目录下所有文件类型

小樊
43
2025-07-24 14:34:25
栏目: 编程语言

readdir 函数用于读取目录中的条目。要使用 readdir 获取目录下所有文件类型,你需要遵循以下步骤:

  1. 包含必要的头文件:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
  1. 打开目录:
DIR *dir = opendir("your_directory_path");
if (dir == NULL) {
    perror("opendir");
    exit(EXIT_FAILURE);
}
  1. 使用 readdir 函数读取目录中的条目:
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
    // 处理每个条目
}
  1. 对于每个条目,使用 stat 函数获取文件类型信息:
struct stat file_stat;
if (stat(entry->d_name, &file_stat) == -1) {
    perror("stat");
    continue;
}
  1. 根据 file_stat.st_mode 的值判断文件类型:
if (S_ISREG(file_stat.st_mode)) {
    printf("%s is a regular file\n", entry->d_name);
} else if (S_ISDIR(file_stat.st_mode)) {
    printf("%s is a directory\n", entry->d_name);
} else if (S_ISCHR(file_stat.st_mode)) {
    printf("%s is a character device\n", entry->d_name);
} else if (S_ISBLK(file_stat.st_mode)) {
    printf("%s is a block device\n", entry->d_name);
} else if (S_ISFIFO(file_stat.st_mode)) {
    printf("%s is a FIFO (pipe)\n", entry->d_name);
} else if (S_ISSOCK(file_stat.st_mode)) {
    printf("%s is a socket\n", entry->d_name);
} else {
    printf("%s is of unknown type\n", entry->d_name);
}
  1. 关闭目录:
closedir(dir);

将以上代码片段组合在一起,你就可以使用 readdir 获取目录下所有文件类型了。注意将 "your_directory_path" 替换为你要读取的目录路径。

0
看了该问题的人还看了