在 CentOS 系统中,readdir
函数用于读取目录中的条目。要判断文件类型,可以使用 struct dirent
结构体中的 d_type
字段。d_type
字段表示文件的类型,它有以下几种可能的值:
以下是一个使用 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;
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
struct stat file_stat;
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
switch (entry->d_type) {
case DT_REG:
printf("%s is a regular file\n", entry->d_name);
break;
case DT_DIR:
printf("%s is a directory\n", entry->d_name);
break;
case DT_LNK:
printf("%s is a symbolic link\n", entry->d_name);
break;
case DT_BLK:
printf("%s is a block device\n", entry->d_name);
break;
case DT_CHR:
printf("%s is a character device\n", entry->d_name);
break;
case DT_FIFO:
printf("%s is a named pipe (FIFO)\n", entry->d_name);
break;
case DT_SOCK:
printf("%s is a socket\n", entry->d_name);
break;
default:
printf("%s is of unknown type\n", entry->d_name);
break;
}
}
closedir(dir);
return EXIT_SUCCESS;
}
编译并运行此程序,传入一个目录作为参数,程序将输出该目录中每个条目的文件类型。