温馨提示×

readdir如何实现文件监控

小樊
53
2025-09-09 14:38:40
栏目: 编程语言

readdir 本身并不直接用于文件监控,而是用于读取目录内容。要实现文件监控,你可以结合 readdir 和其他系统调用或库函数。以下是使用 C 语言和 inotify(Linux 系统)实现文件监控的示例:

  1. 首先,确保你的系统支持 inotify。在 Linux 内核 2.6.13 及更高版本中可用。

  2. 安装 libinotify-dev 库(如果尚未安装):

sudo apt-get install libinotify-dev
  1. 创建一个 C 文件,例如 file_monitor.c,并添加以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <dirent.h>
#include <unistd.h>

#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )

int main(int argc, char **argv)
{
    int length, i = 0;
    int fd;
    int wd;
    char buffer[BUF_LEN];

    // 检查命令行参数
    if (argc != 2) {
        printf("Usage: %s <directory_to_watch>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // 初始化 inotify
    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
        exit(EXIT_FAILURE);
    }

    // 添加要监视的目录
    wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
        exit(EXIT_FAILURE);
    }

    // 读取 inotify 事件
    while (1) {
        length = read(fd, buffer, BUF_LEN);
        if (length < 0) {
            perror("read");
            exit(EXIT_FAILURE);
        }

        while (i < length) {
            struct inotify_event *event = (struct inotify_event *) &buffer[i];
            if (event->len) {
                if (event->mask & IN_CREATE) {
                    printf("File %s created\n", event->name);
                } else if (event->mask & IN_DELETE) {
                    printf("File %s deleted\n", event->name);
                } else if (event->mask & IN_MODIFY) {
                    printf("File %s modified\n", event->name);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

    // 移除监视并关闭文件描述符
    inotify_rm_watch(fd, wd);
    close(fd);

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

这将监视指定目录中的文件更改,并在控制台中显示创建、删除和修改事件。

请注意,这个示例仅适用于 Linux 系统。对于其他操作系统,你可以使用类似的库,如 macOS 上的 FSEvents 或 Windows 上的 ReadDirectoryChangesW

0