在Linux中,readdir
函数用于读取目录中的文件和子目录
以下是一个简单的示例,展示了如何使用readdir
函数读取目录并判断文件类型:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
if (argc != 2) {
printf("Usage: %s <directory>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
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("stat");
continue;
}
// 判断文件类型
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 (named 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);
}
}
closedir(dir);
return 0;
}
这个程序接受一个目录作为命令行参数,然后使用readdir
函数读取目录中的每个条目。对于每个条目,我们使用stat
函数获取文件的stat
信息,然后根据st_mode
字段判断文件类型。