CentOS readdir时间戳处理
导读:在 CentOS 系统中,readdir 函数用于读取目录中的文件和子目录 以下是一个简单的示例,展示了如何使用 readdir 函数读取目录并处理时间戳: #include <stdio.h> #include <std...
在 CentOS 系统中,readdir
函数用于读取目录中的文件和子目录
以下是一个简单的示例,展示了如何使用 readdir
函数读取目录并处理时间戳:
#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");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
// 跳过 "." 和 ".." 目录
if (strcmp(entry->
d_name, ".") == 0 || strcmp(entry->
d_name, "..") == 0) {
continue;
}
// 获取文件的详细信息
char file_path[PATH_MAX];
snprintf(file_path, sizeof(file_path), "./%s", entry->
d_name);
if (stat(file_path, &
file_stat) == -1) {
perror("stat");
continue;
}
// 处理时间戳
char time_str[20];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&
file_stat.st_mtime));
printf("%s: %s\n", entry->
d_name, time_str);
}
closedir(dir);
return 0;
}
在这个示例中,我们首先打开当前目录,然后使用 readdir
函数逐个读取目录中的文件和子目录。对于每个文件或目录,我们使用 stat
函数获取其详细信息,包括修改时间戳(st_mtime
)。最后,我们使用 strftime
函数将时间戳转换为易读的字符串格式,并打印出来。
编译并运行这个程序,你将看到当前目录中所有文件和子目录的名称及其修改时间戳。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: CentOS readdir时间戳处理
本文地址: https://pptw.com/jishu/727368.html