监听到这个事件后读出文件中的内容
时间: 2024-03-11 09:50:29 浏览: 11
好的,以下是修改后的C语言代码,在监听到文件写入事件后,读取文件中的内容并输出:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <fcntl.h>
#define EVENT_SIZE (sizeof(struct inotify_event))
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
int main()
{
int fd, wd;
char buffer[BUF_LEN];
fd = inotify_init();
if (fd < 0) {
fprintf(stderr, "Error: Failed to initialize inotify!\n");
return 1;
}
wd = inotify_add_watch(fd, "test.txt", IN_CLOSE_WRITE);
if (wd < 0) {
fprintf(stderr, "Error: Failed to add watch for file!\n");
close(fd);
return 1;
}
printf("Listening for file writes on test.txt...\n");
while (1) {
int len = read(fd, buffer, BUF_LEN);
if (len < 0) {
fprintf(stderr, "Error: Failed to read inotify events!\n");
break;
}
int i = 0;
while (i < len) {
struct inotify_event* event = (struct inotify_event*) &buffer[i];
if (event->mask & IN_CLOSE_WRITE) {
printf("File written: %s\n", event->name);
int file_fd = open(event->name, O_RDONLY);
if (file_fd < 0) {
fprintf(stderr, "Error: Failed to open file!\n");
break;
}
char file_buffer[BUF_LEN];
int read_len = read(file_fd, file_buffer, BUF_LEN);
if (read_len < 0) {
fprintf(stderr, "Error: Failed to read file!\n");
close(file_fd);
break;
}
printf("File content: %.*s\n", read_len, file_buffer);
close(file_fd);
}
i += EVENT_SIZE + event->len;
}
}
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
```
这个版本的代码在监听到文件写入事件后,使用open()函数打开文件,并使用read()函数读取文件内容到缓冲区,然后输出文件内容。读取的文件内容长度使用%.*s格式化输出,这样可以输出二进制数据,而不会在遇到\0字符时停止输出。注意,这个版本的代码只适用于读取文本文件,如果要读取二进制文件,需要使用其他方法,例如使用二进制文件I/O函数,如fread()和fwrite()。