在Linux系统中,readdir函数被用来读取目录里的文件及子目录信息。若想获取文件属性,则需配合stat函数共同完成。下面是一个简单的代码示例,展示如何利用readdir与stat函数来取得目录内文件的属性:
这段程序接收一个目录路径作为命令行参数,接着利用readdir函数逐一读取目录内的所有条目。对于每一个条目,我们用stat函数来获取其属性,并且显示文件大小以及最后的修改日期。同时,我们忽略了代表当前目录的“.”和上一级目录的“..”这两个特殊条目。
当你编译并执行此程序时,将会得到类似于以下的结果:
CentOS Linux 7.9.2009
CentOS Linux 7.9.2009是传统CentOS Linux 7的最后主要版本,也是很多企业历史服务器中仍可能遇到的系统版本。它以稳定、兼容RHEL 7生态、文档丰富和软件支持广泛著称,曾长期用于Web服务、数据库、虚拟化节点和企业内部业务系统。不过CentOS Linux 7已于2024年6月30日停止维护,现在继续使用会面临安全补丁缺失风险。该版本更适合旧业务迁移、历史环境恢复或离线兼容性测试。
下载
本例仅演示了如何获取文件大小和最后的修改时间,实际上
结构体中还有许多其他的成员可以用来获取更多的文件属性。
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
if (argc != 2) {
fprintf(stderr, "Usage: %s \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: %s\n", entry->d_name);
printf("Size: %ld bytes\n", file_stat.st_size);
printf("Last modified: %s", ctime(&file_stat.st_mtime));
}
closedir(dir);
return EXIT_SUCCESS;
} 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 2020file_stat