如何监视一个文件夹里面的所有子文件夹和文件?

我有一个名为“Datas”的文件夹。 这个文件夹有一个名为“收件箱”的子文件夹,里面有多个“.txt”文件。 这个“数据”文件夹可以修改,最后将有多个子文件夹与“收件箱”子文件夹和“.txt”文件。 我需要监视“收件箱”文件夹中的“数据”文件夹和“.txt”文件。 我怎样才能做到这一点?

INotify只是监视一个文件夹,并在创build子文件夹时popup事件。 如何在创build“.txt”文件时popup事件(在哪个文件夹中)?

我需要C或C ++代码,但我卡住了。 我不知道如何解决这个问题。

从inotify手册页:

IN_CREATE File/directory created in watched directory (*). 

这可以通过捕捉这个事件来完成。

再次从手册页:

  Limitations and caveats Inotify monitoring of directories is not recursive: to monitor subdirectories under a directory, additional watches must be created. This can take a significant amount time for large directory trees. 

所以,你需要自己做递归部分。 你可以从这里看一个例子开始 。 你也应该看看项目通知工具

如在注释中所示的示例 :它监视/tmp/inotify1/tmp/inotify2创建新文件并显示事件

 #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/inotify.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[2]; char buffer[BUF_LEN]; fd = inotify_init(); if ( fd < 0 ) { perror( "inotify_init" ); } wd[0] = inotify_add_watch( fd, "/tmp/inotify1", IN_CREATE); wd[1] = inotify_add_watch (fd, "/tmp/inotify2", IN_CREATE); while (1){ struct inotify_event *event; length = read( fd, buffer, BUF_LEN ); if ( length < 0 ) { perror( "read" ); } event = ( struct inotify_event * ) &buffer[ i ]; if ( event->len ) { if (event->wd == wd[0]) printf("%s\n", "In /tmp/inotify1: "); else printf("%s\n", "In /tmp/inotify2: "); if ( event->mask & IN_CREATE ) { if ( event->mask & IN_ISDIR ) { printf( "The directory %s was created.\n", event->name ); } else { printf( "The file %s was created.\n", event->name ); } } } } ( void ) inotify_rm_watch( fd, wd[0] ); ( void ) inotify_rm_watch( fd, wd[1]); ( void ) close( fd ); exit( 0 ); } 

测试运行:

 shadyabhi@archlinux ~ $ ./a.out In /tmp/inotify1: The file abhijeet was created. In /tmp/inotify2: The file rastogi was created. ^C shadyabhi@archlinux ~ $ 

也有fanotify 。 有了它,您可以在整个安装点上设置一个手表。 看看这里的例子代码。