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

how to print name of newly created file(s) within a directory in C?

此代码扫描目录中新创建的文件,但是“%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;
}

当您收到一个事件时,您正在打印 target,但是 target 永远不会被修改。

创建文件的名称存储在event->name中。这就是您要打印的内容。

printf("The file %s has been created\n", event->name);