溫馨提示×

readdir如何檢測文件修改時間

小樊
40
2025-08-02 07:24:22
欄目: 編程語言

readdir 函數本身并不直接提供文件的修改時間。它主要用于讀取目錄中的條目。但是,你可以結合其他函數來獲取文件的修改時間。以下是一個使用 C 語言的示例,展示了如何使用 opendir、readdirstat 函數來獲取目錄中文件的修改時間:

#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_str[100];
        strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_mtime));

        printf("File: %s, Modified time: %s\n", entry->d_name, time_str);
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

這個示例程序首先打開當前目錄,然后使用 readdir 函數讀取目錄中的每個條目。對于每個條目,它使用 stat 函數獲取文件的詳細信息,包括修改時間。最后,它將修改時間轉換為可讀的字符串格式并打印出來。

請注意,這個示例使用了 POSIX 標準庫函數,因此它應該在支持 POSIX 的系統(如 Linux 和 macOS)上運行。如果你使用的是 Windows 系統,你需要使用 Windows API 函數(如 FindFirstFile、FindNextFileGetFileTime)來實現類似的功能。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女