Skip to content

Commit 7403e9e

Browse files
Create file_owl.cpp
>> g++ -o file_owl file_owl.cpp && ./file_owl
1 parent baa99e8 commit 7403e9e

1 file changed

Lines changed: 89 additions & 0 deletions

File tree

src/file_owl.cpp

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
#include <iostream>
2+
#include <string>
3+
#include <unistd.h>
4+
#include <sys/inotify.h>
5+
#include <limits.h>
6+
#include <dirent.h>
7+
8+
// Function to add a watch recursively
9+
void add_watch(int fd, const std::string& path) {
10+
// Add a watch for the current directory
11+
int wd = inotify_add_watch(fd, path.c_str(), IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVE);
12+
if (wd == -1) {
13+
perror("inotify_add_watch");
14+
return;
15+
}
16+
17+
// Open the directory and iterate through its entries
18+
DIR* dir = opendir(path.c_str());
19+
if (!dir) {
20+
perror("opendir");
21+
return;
22+
}
23+
24+
struct dirent* entry;
25+
while ((entry = readdir(dir)) != nullptr) {
26+
std::string entry_path = path + "/" + entry->d_name;
27+
28+
// Skip "." and ".."
29+
if (std::string(entry->d_name) == "." || std::string(entry->d_name) == "..") {
30+
continue;
31+
}
32+
33+
// If it's a directory, add a watch for it and its contents
34+
if (entry->d_type == DT_DIR) {
35+
add_watch(fd, entry_path);
36+
}
37+
}
38+
39+
closedir(dir);
40+
}
41+
42+
int main() {
43+
const std::string directory_to_watch = "/home/dir/owl/"; // Change this to your target directory
44+
45+
// Create an inotify instance
46+
int fd = inotify_init();
47+
if (fd == -1) {
48+
perror("inotify_init");
49+
return EXIT_FAILURE;
50+
}
51+
52+
// Add watches recursively
53+
add_watch(fd, directory_to_watch);
54+
55+
// Buffer to store inotify events
56+
char buffer[4096] __attribute__ ((aligned(__alignof__(struct inotify_event))));
57+
while (true) {
58+
int length = read(fd, buffer, sizeof(buffer));
59+
if (length < 0) {
60+
perror("read");
61+
break;
62+
}
63+
64+
for (char* ptr = buffer; ptr < buffer + length; ) {
65+
struct inotify_event* event = reinterpret_cast<struct inotify_event*>(ptr);
66+
67+
std::string event_name = (event->len > 0) ? event->name : "unknown";
68+
std::cout << "Event: ";
69+
if (event->mask & IN_CREATE) {
70+
std::cout << "CREATE";
71+
} else if (event->mask & IN_DELETE) {
72+
std::cout << "DELETE";
73+
} else if (event->mask & IN_MODIFY) {
74+
std::cout << "MODIFY";
75+
} else if (event->mask & IN_MOVED_FROM || event->mask & IN_MOVED_TO) {
76+
std::cout << "MOVE";
77+
} else {
78+
std::cout << "UNKNOWN";
79+
}
80+
std::cout << " on " << event_name << std::endl;
81+
82+
ptr += sizeof(struct inotify_event) + event->len;
83+
}
84+
}
85+
86+
// Clean up
87+
close(fd);
88+
return EXIT_SUCCESS;
89+
}

0 commit comments

Comments
 (0)