在Ubuntu中,readdir
函数是用于读取目录内容的。默认情况下,readdir
会返回目录中的所有文件和子目录,而不区分文件类型。如果你想要对不同类型的文件进行不同的处理,你需要在获取到文件名后,使用其他函数来进一步检查文件的类型。
以下是一个简单的示例,展示了如何使用readdir
以及stat
函数来判断文件类型:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>
", argv[0]);
return EXIT_FAILURE;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
// 构建文件的完整路径
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
// 获取文件状态
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 判断文件类型
if (S_ISREG(file_stat.st_mode)) {
printf("Regular file: %s
", entry->d_name);
} else if (S_ISDIR(file_stat.st_mode)) {
printf("Directory: %s
", entry->d_name);
} else if (S_ISCHR(file_stat.st_mode)) {
printf("Character device: %s
", entry->d_name);
} else if (S_ISBLK(file_stat.st_mode)) {
printf("Block device: %s
", entry->d_name);
} else if (S_ISFIFO(file_stat.st_mode)) {
printf("FIFO (named pipe): %s
", entry->d_name);
} else if (S_ISSOCK(file_stat.st_mode)) {
printf("Socket: %s
", entry->d_name);
} else {
printf("Other type: %s
", entry->d_name);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
在这个示例中,我们首先使用opendir
打开一个目录,然后使用readdir
读取目录中的每个条目。对于每个条目,我们使用snprintf
构建文件的完整路径,并使用stat
获取文件的状态信息。然后,我们使用S_ISREG
、S_ISDIR
等宏来检查文件的类型,并根据类型打印相应的消息。
请注意,这个示例仅用于演示目的,实际应用中可能需要更复杂的错误处理和逻辑。此外,如果你想要检查符号链接或其他特殊文件类型,你可能需要使用其他函数,如lstat
。