
opendir() 函数本身只负责打开目录流,并非直接获取文件属性。要获取目录中文件的属性信息,需要结合 readdir() 和 stat() 等函数。以下示例代码演示如何在类 Unix 系统(如 Linux 和 macOS)中实现:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_info;
char filepath[1024];
// 打开当前目录
dir = opendir(".");
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;
// 构造完整文件路径
snprintf(filepath, sizeof(filepath), "./%s", entry->d_name);
// 获取文件属性
if (stat(filepath, &file_info) == -1) {
perror("stat");
closedir(dir);
return EXIT_FAILURE;
}
// 打印文件属性信息
printf("文件名: %s\n", entry->d_name);
printf("文件大小: %lld 字节\n", (long long)file_info.st_size);
printf("最后修改时间: %s", ctime(&file_info.st_mtime));
printf("---------------------\n");
}
// 关闭目录流
closedir(dir);
return EXIT_SUCCESS;
}这段代码首先打开当前目录,然后循环读取每个目录项。对于每个项,它构建完整的路径,并使用 stat() 函数获取文件属性,包括文件大小和最后修改时间。最后,它打印这些信息。 请注意,此代码仅适用于类 Unix 系统。Windows 系统需要使用不同的 API 函数来实现相同的功能。
以上就是如何用copendir获取目录文件属性的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号