readdir如何获取文件最后访问时间
导读:在C语言中,你可以使用readdir函数来读取目录中的文件。但是,readdir函数本身并不提供获取文件最后访问时间的功能。要获取文件的最后访问时间,你需要使用stat函数。 以下是一个简单的示例,展示了如何使用readdir和stat函数...
在C语言中,你可以使用readdir函数来读取目录中的文件。但是,readdir函数本身并不提供获取文件最后访问时间的功能。要获取文件的最后访问时间,你需要使用stat函数。
以下是一个简单的示例,展示了如何使用readdir和stat函数来获取目录中文件的最后访问时间:
#include <
stdio.h>
#include <
stdlib.h>
#include <
dirent.h>
#include <
sys/stat.h>
#include <
time.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
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;
}
// 构建文件的完整路径
char file_path[1024];
snprintf(file_path, sizeof(file_path), "./%s", entry->
d_name);
// 获取文件的stat信息
if (stat(file_path, &
file_stat) == -1) {
perror("stat");
continue;
}
// 将最后访问时间转换为可读格式并打印
char time_buf[100];
strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&
file_stat.st_atime));
printf("%s: Last accessed time: %s\n", entry->
d_name, time_buf);
}
closedir(dir);
return EXIT_SUCCESS;
}
这个程序首先打开当前目录,然后使用readdir函数读取目录中的每个文件。对于每个文件,它使用stat函数获取文件的stat信息,其中包括最后访问时间(st_atime)。然后,它将最后访问时间转换为可读的字符串格式,并将其打印到屏幕上。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: readdir如何获取文件最后访问时间
本文地址: https://pptw.com/jishu/758508.html
