温馨提示×

如何利用readdir实现目录监控

小樊
33
2025-12-07 10:25:02
栏目: 编程语言

readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要利用 readdir 实现目录监控,你需要定期调用 readdir 函数来检查目录内容是否发生变化。以下是一个简单的示例:

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

void monitor_directory(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf, prev_statbuf;
    int first_run = 1;

    // 获取目录的初始状态
    if (stat(path, &prev_statbuf) != 0) {
        perror("stat");
        return;
    }

    dir = opendir(path);
    if (!dir) {
        perror("opendir");
        return;
    }

    while (1) {
        // 读取目录内容
        entry = readdir(dir);

        if (entry == NULL) {
            perror("readdir");
            closedir(dir);
            return;
        }

        // 跳过当前目录和上级目录
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 获取文件/目录的新状态
        char new_path[PATH_MAX];
        snprintf(new_path, sizeof(new_path), "%s/%s", path, entry->d_name);
        if (stat(new_path, &statbuf) != 0) {
            perror("stat");
            continue;
        }

        // 检查文件/目录是否发生变化
        if (first_run || memcmp(&prev_statbuf, &statbuf, sizeof(statbuf)) != 0) {
            printf("Change detected: %s\n", new_path);

            // 更新 prev_statbuf 以便下次比较
            memcpy(&prev_statbuf, &statbuf, sizeof(statbuf));
        }

        // 如果是第一次运行,设置 first_run 为 0
        if (first_run) {
            first_run = 0;
        }

        // 等待一段时间再次检查
        sleep(1);
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return 1;
    }

    monitor_directory(argv[1]);

    return 0;
}

这个示例程序会监控指定的目录,并在检测到任何变化时打印出变化的文件或目录。请注意,这个程序只是一个简单的示例,实际应用中可能需要考虑更多的因素,例如错误处理、性能优化等。

0