首页主机资讯Linux readdir时间戳处理

Linux readdir时间戳处理

时间2025-12-03 22:24:03发布访客分类主机资讯浏览496
导读:在Linux中,readdir函数用于读取目录中的文件和子目录 以下是一个简单的示例,展示了如何使用readdir函数读取目录并处理时间戳: #include <stdio.h> #include <stdlib.h>...

在Linux中,readdir函数用于读取目录中的文件和子目录

以下是一个简单的示例,展示了如何使用readdir函数读取目录并处理时间戳:

#include <
    stdio.h>
    
#include <
    stdlib.h>
    
#include <
    dirent.h>
    
#include <
    sys/stat.h>
    
#include <
    time.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;

        }
    

        // 处理时间戳
        char time_buf[20];
    
        strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&
    file_stat.st_mtime));
    
        printf("%s: %s\n", entry->
    d_name, time_buf);

    }
    

    closedir(dir);
    
    return EXIT_SUCCESS;

}
    

这个程序接受一个目录作为命令行参数,然后使用readdir函数读取目录中的所有文件和子目录。对于每个条目,它使用stat函数获取文件的状态信息,包括修改时间戳(st_mtime)。然后,它使用strftime函数将时间戳格式化为易读的字符串,并将其打印到屏幕上。

编译并运行此程序,您将看到类似以下的输出:

file1.txt: 2022-01-01 12:34:56
file2.txt: 2022-01-02 12:34:56
subdir: 2022-01-03 12:34:56

这显示了目录中每个文件的名称及其最后修改时间。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Linux readdir时间戳处理
本文地址: https://pptw.com/jishu/762838.html
Debian AppImage使用教程 Linux readdir文件排序方法

游客 回复需填写必要信息