在 CentOS 系统中,使用 readdir 函数可以读取目录中的文件和子目录。为了判断文件类型,你可以结合使用 dirent.h 中定义的 DT_* 常量。以下是一个简单的示例,展示了如何使用 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) {
// 获取文件的 inode 信息
if (stat(argv[1] "/" entry->d_name, &file_stat) == -1) {
perror("stat");
continue;
}
// 判断文件类型
switch (file_stat.st_mode & DT_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 FIFO (named pipe)\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 0;
}
这个程序接受一个目录作为命令行参数,然后使用 readdir 函数读取目录中的每个条目。对于每个条目,我们使用 stat 函数获取文件的 inode 信息,然后根据 st_mode 字段与 DT_TYPE 常量的按位与结果判断文件类型。
编译并运行这个程序,你可以看到目录中每个文件的类型。