
在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: %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;
}这段程序接收一个目录路径作为命令行参数,接着利用readdir函数逐一读取目录内的所有条目。对于每一个条目,我们用stat函数来获取其属性,并且显示文件大小以及最后的修改日期。同时,我们忽略了代表当前目录的“.”和上一级目录的“..”这两个特殊条目。
当你编译并执行此程序时,将会得到类似于以下的结果:
<code>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</code>
本例仅演示了如何获取文件大小和最后的修改时间,实际上file_stat结构体中还有许多其他的成员可以用来获取更多的文件属性。
以上就是Linux readdir如何实现文件属性获取的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号