阅读量:1
在Linux中,readdir函数用于读取目录中的文件和子目录。当你使用readdir读取目录时,它会返回一个struct dirent结构体数组,其中包含了目录中的每个文件和子目录的信息。struct dirent结构体中的d_mtime字段表示文件或目录的最后修改时间。
d_mtime字段是一个time_t类型的值,它表示自1970年1月1日(UTC)以来的秒数。你可以使用C语言中的ctime库函数将time_t类型的时间戳转换为可读的字符串格式。以下是一个简单的示例:
#include
#include
#include
#include
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
char path[1024];
snprintf(path, sizeof(path), "./%s", entry->d_name);
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
char time_str[100];
ctime_r(&file_stat.st_mtime, time_str);
time_str[strcspn(time_str, "\n")] = 0; // Remove newline character
printf("%s - Last modified: %s", entry->d_name, time_str);
}
closedir(dir);
return 0;
}
这个示例程序会打开当前目录(.),然后使用readdir读取目录中的每个文件和子目录。对于每个条目,我们使用stat函数获取文件的元数据,包括最后修改时间。然后我们使用ctime_r函数将time_t类型的时间戳转换为可读的字符串格式,并打印出来。
以上就是关于“Linux readdir的时间戳处理”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm