在Debian系统中,readdir函数用于读取目录中的条目。它返回一个指向dirent结构体的指针,该结构体包含了关于目录条目的信息,如文件名、文件类型等。
要识别readdir返回的文件类型,可以检查dirent结构体中的d_type成员。d_type成员是一个unsigned char类型的值,表示文件类型。以下是一些常见的d_type值及其对应的文件类型:
示例代码:
#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) {
printf("%s\n", entry->d_name);
int type = entry->d_type;
switch (type) {
case DT_REG:
printf(" Type: Regular file\n");
break;
case DT_DIR:
printf(" Type: Directory\n");
break;
case DT_LNK:
printf(" Type: Symbolic link\n");
break;
case DT_BLK:
printf(" Type: Block device\n");
break;
case DT_CHR:
printf(" Type: Character device\n");
break;
case DT_FIFO:
printf(" Type: Named pipe (FIFO)\n");
break;
case DT_SOCK:
printf(" Type: Socket\n");
break;
default:
printf(" Type: Unknown\n");
break;
}
}
closedir(dir);
return EXIT_SUCCESS;
}
编译并运行此程序,它将列出指定目录中的所有条目,并显示每个条目的文件类型。