如何在C中的目录中打印新创建的文件的名称?

问题描述 投票:0回答:1

此代码扫描目录中新创建的文件,但是“%s”应包含新文件的名称,这不会发生。

我可以想象这里写了不必要的代码片段,但是对C语言非常不熟悉我很高兴它在这一点上编译(实际上识别新文件)!

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <sys/inotify.h>

int main (int argc, char *argv[])
{
        char target[FILENAME_MAX];
        int result;
        int fd;
        int wd; /* watch descriptor */
        const int event_size = sizeof(struct inotify_event);
        const int buf_len = 1024 * (event_size + FILENAME_MAX);

        fd = inotify_init();

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

        wd = inotify_add_watch(fd, "/home/joe/Documents", IN_CREATE);

        while (1) {
                char buff[buf_len];
                int no_of_events, count = 0;

                no_of_events = read (fd, buff, buf_len);

                while (count < no_of_events) {
                        struct inotify_event *event = (struct inotify_event *)&buff[count];

                        if (event->len) {
                                if (event->mask & IN_CREATE)
                                        if(!(event->mask & IN_ISDIR)) {
                                                printf("The file %s has been created\n", target);
                                                fflush(stdout);
                                        }
                        }
                        count += event_size + event->len;
                }
        }

        return 0;
}
c loops inotify
1个回答
1
投票

当你得到一个事件时,你打印出target,但target永远不会被修改。

创建的文件的名称存储在event->name中。这就是你想要打印的东西。

printf("The file %s has been created\n", event->name);
© www.soinside.com 2019 - 2024. All rights reserved.