温馨提示×

如何利用readdir实现文件监控和日志记录

小樊
51
2025-09-28 08:02:36
栏目: 编程语言

readdir 是一个用于读取目录内容的函数,通常在 C/C++ 语言中使用。要利用 readdir 实现文件监控和日志记录,你需要定期检查目录内容的变化,并将变化记录到日志文件中。以下是一个简单的示例:

  1. 首先,确保你的系统上安装了必要的开发工具和库。

  2. 创建一个名为 file_monitor.c 的 C 文件,并添加以下代码:

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

#define LOG_FILE "file_monitor.log"

void log_message(const char *message) {
    FILE *log_file = fopen(LOG_FILE, "a");
    if (log_file == NULL) {
        perror("Failed to open log file");
        return;
    }

    time_t now = time(NULL);
    fprintf(log_file, "%s: %s\n", ctime(&now), message);
    fclose(log_file);
}

void monitor_directory(const char *path) {
    DIR *dir = opendir(path);
    if (dir == NULL) {
        perror("Failed to open directory");
        return;
    }

    struct dirent *entry;
    struct stat statbuf;
    char last_statbuf[PATH_MAX];

    while ((entry = readdir(dir)) != NULL) {
        snprintf(last_statbuf, sizeof(last_statbuf), "%s/%s", path, entry->d_name);
        if (stat(last_statbuf, &statbuf) == -1) {
            perror("Failed to get file status");
            continue;
        }

        // Check if the file is new or has been modified
        if (entry->d_type == DT_REG) {
            FILE *last_stat_file = fopen(last_statbuf, "r");
            if (last_stat_file == NULL) {
                log_message(entry->d_name);
                fclose(last_stat_file);
                continue;
            }

            int new_file = fscanf(last_stat_file, "%ld", &statbuf.st_mtime) != 1;
            fclose(last_stat_file);

            if (new_file || statbuf.st_mtime != *(long *)last_statbuf) {
                log_message(entry->d_name);
            }
        }
    }

    closedir(dir);
}

int main() {
    const char *path = ".";

    while (1) {
        monitor_directory(path);
        sleep(60); // Check the directory every 60 seconds
    }

    return 0;
}
  1. 编译并运行程序:
gcc file_monitor.c -o file_monitor
./file_monitor

这个程序将每 60 秒检查一次当前目录(.)的内容,并将新文件或已修改的文件记录到 file_monitor.log 文件中。你可以根据需要调整检查间隔和监控目录。

请注意,这个示例仅适用于简单的文件监控场景。在实际应用中,你可能需要处理更多的边缘情况,例如符号链接、权限问题等。此外,对于更高级的文件监控需求,你可以考虑使用专门的库,如 inotify(Linux)或 ReadDirectoryChangesW(Windows)。

0