alt=”linux readdir如何实现文件属性获取” />
在Linux系统中,readdir函数被用来读取目录里的文件及子目录信息。若想获取文件属性,则需配合stat函数共同完成。下面是一个简单的代码示例,展示如何利用readdir与stat函数来取得目录内文件的属性:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/types.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>n", argv[0]); return EXIT_FAILURE; } dir = opendir(argv[1]); if (dir == NULL) { perror("opendir"); return EXIT_FAILURE; } while ((entry = readdir(dir)) != NULL) { // 跳过当前目录和上级目录的特殊条目 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 组合完整的文件路径 char path[PATH_MAX]; snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name); // 获取文件属性 if (stat(path, &file_stat) == -1) { perror("stat"); continue; } // 显示文件属性 printf("File: %sn", entry->d_name); printf("Size: %ld bytesn", file_stat.st_size); printf("Last modified: %s", ctime(&file_stat.st_mtime)); } closedir(dir); return EXIT_SUCCESS; }
这段程序接收一个目录路径作为命令行参数,接着利用readdir函数逐一读取目录内的所有条目。对于每一个条目,我们用stat函数来获取其属性,并且显示文件大小以及最后的修改日期。同时,我们忽略了代表当前目录的“.”和上一级目录的“..”这两个特殊条目。
当你编译并执行此程序时,将会得到类似于以下的结果:
File: example.txt Size: 1234 bytes Last modified: Thu Oct 15 14:23:12 2020 File: log.txt Size: 5678 bytes Last modified: Wed Oct 16 10:45:34 2020
本例仅演示了如何获取文件大小和最后的修改时间,实际上file_stat结构体中还有许多其他的成员可以用来获取更多的文件属性。