readdir
函数用于读取目录中的条目。要使用 readdir
获取目录下所有文件类型,你需要遵循以下步骤:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
DIR *dir = opendir("your_directory_path");
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
readdir
函数读取目录中的条目:struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 处理每个条目
}
stat
函数获取文件类型信息:struct stat file_stat;
if (stat(entry->d_name, &file_stat) == -1) {
perror("stat");
continue;
}
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);
}
closedir(dir);
将以上代码片段组合在一起,你就可以使用 readdir
获取目录下所有文件类型了。注意将 "your_directory_path"
替换为你要读取的目录路径。