温馨提示×

Linux readdir如何检测文件变化

小樊
38
2025-12-09 10:00:12
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的文件和子目录。如果你想要检测目录中的文件变化,你可以在两次调用readdir之间进行比较。以下是一个简单的示例,展示了如何使用readdir检测目录中的文件变化:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int main() {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;
    char *path;
    int i = 0;

    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

    // 第一次读取目录
    while ((entry = readdir(dir)) != NULL) {
        path = malloc(strlen(entry->d_name) + 2);
        sprintf(path, "./%s", entry->d_name);

        stat(path, &file_stat);
        printf("File %d: %s\n", i++, entry->d_name);
        printf("Size: %ld\n", file_stat.st_size);
        printf("Last modified: %s", ctime(&file_stat.st_mtime));

        free(path);
    }

    closedir(dir);

    // 等待一段时间
    sleep(5);

    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

    // 第二次读取目录
    while ((entry = readdir(dir)) != NULL) {
        path = malloc(strlen(entry->d_name) + 2);
        sprintf(path, "./%s", entry->d_name);

        stat(path, &file_stat);
        printf("File %d: %s\n", i++, entry->d_name);
        printf("Size: %ld\n", file_stat.st_size);
        printf("Last modified: %s", ctime(&file_stat.st_mtime));

        free(path);
    }

    closedir(dir);

    return 0;
}

这个示例程序首先打开当前目录(.),然后两次调用readdir函数读取目录中的文件。在两次读取之间,程序等待5秒钟。这样,如果在这段时间内目录中的文件发生了变化(例如,添加、删除或修改文件),第二次读取时就会检测到这些变化。

请注意,这个示例程序仅用于演示目的,实际应用中可能需要更复杂的逻辑来处理文件变化。例如,你可以将两次读取的结果存储在数据结构中,并在比较时考虑文件的添加、删除和修改操作。

0