如何监视包含所有子文件夹和文件的文件夹
How to monitor a folder with all subfolders and files inside?
我有一个名为"Datas"的文件夹。这个文件夹有一个名为"收件箱"的子文件夹,里面有多个".txt"文件。这个"数据"文件夹可以修改,最终会有多个子文件夹,其中包含"收件箱"子文件夹和".txt"文件。我需要监控"收件箱"文件夹中的"Datas"文件夹和".txt"文件。我该怎么做?
INotify只是监视一个文件夹,并在创建子文件夹时弹出事件。如何在创建".txt"文件时弹出事件(在哪个文件夹中)?
我需要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
&CCD_ 2用于创建的新文件&显示事件
#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("%sn", "In /tmp/inotify1: ");
else printf("%sn", "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
。有了它,你可以在一个完整的安装点上安装手表。请查看此处的示例代码。
相关文章:
- 如何将更多文件夹添加到c++include路径
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何在文档文件夹中创建目录
- "assimp/config.h"找不到,但它在文件夹中
- C++入门 5 版:类消息和文件夹
- 我可以在 Arduino 的库文件夹之外安装库吗?
- 如何按文件扩展名引用文件夹中的文件
- 在QTreeView中仅显示共享驱动器和文件夹
- 加载与引用 .NET DLL 位于同一文件夹中的引用的 .NET DLL 时"Not found"异常
- 介子复制/安装头文件到输出目录并保持文件夹结构
- vcruntime.h 从 Windows 包含文件夹中丢失?
- 在文件夹迭代上实现 RAII
- 使用 Powershell 命令将 cpp 文件的文件夹编译为 GNU 的 g++
- 使文件夹中的所有文件可供所有项目(子目录)访问
- 无法使用 CMake 从其他文件夹添加源文件
- 如何在安卓工作室中将c ++头文件从一个文件夹导入到另一个文件夹?
- 对单元测试(googletest)和项目/文件夹/文件的混淆
- 设计文件夹/文件系统