读取目录下所有文件(包括子目录)
Linux C 下读取目录要用到结构体 struct dirent
。在头文件 #include <dirent.h>
中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| struct dirent { __ino64_t d_ino; // inode number 索引节点号 __off64_t d_off; // offset to this dirent 在目录文件中的偏移 unsigned short int d_reclen; // length of this d_name 文件名长度 unsigned char d_type; // the type of d_name 文件类型 char d_name[256]; /* We must not include limits.h! 文件名,最长 255 字符 */ }; enum { DT_UNKNOWN = 0, DT_FIFO = 1, // 命名管道 DT_CHR = 2, // 字符设备 DT_DIR = 4, // 目录 DT_BLK = 6, // 块设备 DT_REG = 8, // 常规文件 DT_LNK = 10, // 符号链接 DT_SOCK = 12, // 套接字 DT_WHT = 14 };
|
注意:部分 linux 文件系统,例如 xfs 不支持 d_type,当使用 d_type 时,所有文件/目录的 d_type 会一直为空,即 0(DT_UNKNOWN)。无法判断文件类型,所以需要 stat 函数。
1. 读取目录下的所有文件名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const char* dir_str = "/proc"; DIR* dir = opendir(dir_str); if (dir == NULL) { perror("open dir err: "); exit(-1); } struct dirent* ptr; while ((ptr = readdir(dir)) != NULL) { if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) { continue; } else if (ptr->d_type & DT_REG) { printf("file: %s\n", ptr->d_name); } else if (ptr->d_type & DT_LNK) { printf("link file: %s\n", ptr->d_name); } else if (ptr->d_type & DT_DIR) { printf("dir: %s\n", ptr->d_name); } } closedir(dir);
|