侦测指定文件夹中指定文件的创建、删除、修改动作

要在Linux环境下侦测文件夹中文件的创建、删除和修改动作,可以使用`inotify`库。以下是一个使用`inotify`来监控指定文件夹中文件活动的示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <unistd.h>

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

int main() {
    int length, i = 0;
    int fd;
    int wd;
    char buffer[EVENT_BUF_LEN];

    // 创建inotify实例
    fd = inotify_init();

    if (fd < 0) {
        perror("inotify_init");
    }

    // 监控"/tmp"目录
    wd = inotify_add_watch(fd, "/tmp", IN_CREATE | IN_DELETE | IN_MODIFY);

    if (wd == -1) {
        printf("Could not watch : /tmp\n");
    } else {
        printf("Watching : /tmp\n");
    }

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

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

    // 清理
    inotify_rm_watch(fd, wd);
    close(fd);
}


这段代码会监控`/tmp`目录下的文件创建、删除和修改事件,并打印出相应的文件名和事件类型。你可以修改`inotify_add_watch`函数的第二个参数来指定其他目录。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值