在linux中,readdir函数被广泛用于读取目录中的文件和子目录。本文将通过一个简单的示例,展示如何使用readdir函数来读取目录并判断文件类型。
<code>#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <limits.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
if (argc != 2) {
printf("使用方法: %s <目录>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("无法打开目录");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
// 构建文件的完整路径
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
// 获取文件的stat信息
if (stat(path, &file_stat) == -1) {
perror("获取文件信息失败");
continue;
}
// 判断文件类型
if (S_ISREG(file_stat.st_mode)) {
printf("%s 是一个普通文件\n", entry->d_name);
} else if (S_ISDIR(file_stat.st_mode)) {
printf("%s 是一个目录\n", entry->d_name);
} else if (S_ISCHR(file_stat.st_mode)) {
printf("%s 是一个字符设备\n", entry->d_name);
} else if (S_ISBLK(file_stat.st_mode)) {
printf("%s 是一个块设备\n", entry->d_name);
} else if (S_ISFIFO(file_stat.st_mode)) {
printf("%s 是一个FIFO(命名管道)\n", entry->d_name);
} else if (S_ISSOCK(file_stat.st_mode)) {
printf("%s 是一个套接字\n", entry->d_name);
} else {
printf("%s 是一个未知类型的文件\n", entry->d_name);
}
}
closedir(dir);
return 0;
}</code>
上述程序接收一个目录作为命令行参数,并使用readdir函数读取该目录中的每个条目。对于每个条目,我们利用stat函数获取文件的stat信息,并根据st_mode字段来判断文件类型。这样,我们就能轻松地识别出目录中的各种文件类型,如普通文件、目录、字符设备、块设备、命名管道和套接字等。










