在 CentOS 系统中,readdir 函数用于读取目录中的文件和子目录。要识别文件类型,可以使用 stat 函数来获取文件的元数据,然后根据文件类型标志进行判断。
以下是一个简单的示例,展示了如何使用 readdir 和 stat 函数来识别 CentOS 中的文件类型:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.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 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
// 获取文件的完整路径
char file_path[PATH_MAX];
snprintf(file_path, sizeof(file_path), "%s/%s", argv[1], entry->d_name);
// 获取文件的元数据
if (stat(file_path, &file_stat) == -1) {
perror("stat");
continue;
}
// 根据文件类型标志进行判断
switch (file_stat.st_mode & S_IFMT) {
case S_IFREG:
printf("%s is a regular file.
", entry->d_name);
break;
case S_IFDIR:
printf("%s is a directory.
", entry->d_name);
break;
case S_IFCHR:
printf("%s is a character device.
", entry->d_name);
break;
case S_IFBLK:
printf("%s is a block device.
", entry->d_name);
break;
case S_IFIFO:
printf("%s is a named pipe (FIFO).
", entry->d_name);
break;
case S_IFSOCK:
printf("%s is a socket.
", entry->d_name);
break;
default:
printf("%s is of unknown type.
", entry->d_name);
break;
}
}
closedir(dir);
return 0;
}
编译并运行此程序,它将列出指定目录中的所有文件和子目录,并显示它们的类型。例如:
gcc file_type_identification.c -o file_type_identification
./file_type_identification /path/to/directory
请注意,这个示例仅用于演示目的,实际应用中可能需要根据具体需求进行调整。