在Linux中,readdir
函数用于读取目录中的条目。但是,readdir
本身并不直接提供文件类型信息。要识别文件类型,你可以结合使用readdir
和其他函数,例如stat
。
以下是一个简单的示例,展示了如何使用readdir
和stat
函数来识别文件类型:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
void print_file_type(const char *path) {
struct stat path_stat;
int ret = stat(path, &path_stat);
if (ret == -1) {
perror("stat");
return;
}
if (S_ISREG(path_stat.st_mode)) {
printf("%s is a regular file\n", path);
} else if (S_ISDIR(path_stat.st_mode)) {
printf("%s is a directory\n", path);
} else if (S_ISCHR(path_stat.st_mode)) {
printf("%s is a character device\n", path);
} else if (S_ISBLK(path_stat.st_mode)) {
printf("%s is a block device\n", path);
} else if (S_ISFIFO(path_stat.st_mode)) {
printf("%s is a FIFO (named pipe)\n", path);
} else if (S_ISSOCK(path_stat.st_mode)) {
printf("%s is a socket\n", path);
} else {
printf("%s is of unknown type\n", path);
}
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
DIR *dir = opendir(argv[1]);
if (!dir) {
perror("opendir");
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
print_file_type(path);
}
closedir(dir);
return EXIT_SUCCESS;
}
这个程序接受一个目录作为命令行参数,然后使用readdir
函数读取目录中的条目。对于每个条目,我们使用snprintf
函数构建完整的文件路径,然后调用print_file_type
函数来识别文件类型。print_file_type
函数使用stat
函数获取文件的元数据,并根据st_mode
字段的值来判断文件类型。