linux

readdir如何获取最后修改时间

小樊
44
2025-09-17 14:43:00
栏目: 编程语言

在编程中,readdir 函数通常用于读取目录中的条目。然而,readdir 本身并不直接提供文件的最后修改时间。要获取文件的最后修改时间,你需要使用其他函数来获取这个信息。

以下是在不同编程语言中获取文件最后修改时间的示例:

C语言(使用dirent.hsys/stat.h

#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 path[1024];
        snprintf(path, sizeof(path), "./%s", entry->d_name);

        // 获取文件的stat信息
        if (stat(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("File: %s, Last Modified: %s\n", entry->d_name, time_str);
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

Python(使用osos.path模块)

import os
import time

for entry in os.scandir('.'):
    if entry.is_file():
        # 获取文件的最后修改时间
        mod_time = os.path.getmtime(entry.path)
        # 转换并打印最后修改时间
        print(f"File: {entry.name}, Last Modified: {time.ctime(mod_time)}")

Node.js(使用fs模块)

const fs = require('fs');
const path = require('path');

fs.readdir('.', (err, files) => {
    if (err) {
        return console.error('Unable to scan directory: ' + err);
    } 
    files.forEach(file => {
        const filePath = path.join(__dirname, file);
        fs.stat(filePath, (err, stats) => {
            if (err) {
                return console.error('Unable to retrieve file stats: ' + err);
            }
            // 转换并打印最后修改时间
            console.log(`File: ${file}, Last Modified: ${new Date(stats.mtime).toLocaleString()}`);
        });
    });
});

在这些示例中,我们首先读取目录中的每个条目,然后使用相应的系统调用或库函数来获取文件的最后修改时间,并将其格式化为可读的字符串形式。注意,这些示例假设你有足够的权限来访问目录和文件。

0
看了该问题的人还看了