
Bard fails miserably at recursive programming where ChatGPT gave an almost finished result.
I asked both to write a C++ program given a folder to monitor its contents and recurs down through all sub folders and monitor those files too.
At the moment, Bard hasn’t got a grip on recursive programming. ChatGPT came out the clear winner. Although I did have to coax it to get it to include the right header files.
The final result definitely wouldn’t be production worthy but a good start to show how to work on this particular task type.
#include <iostream>
#include <sys/inotify.h>
#include <unistd.h>
#include <cstring>
#include <vector>
#include <dirent.h>
#define EVENT_SIZE (sizeof(struct inotify_event))
#define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
void monitorDirectory(const char* directory, int fd, std::vector<int>& watchDescriptors) {
// Add a watch for the specified directory
int wd = inotify_add_watch(fd, directory, IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO);
if (wd < 0) {
std::cerr << "Failed to add watch for directory: " << directory << std::endl;
return;
}
watchDescriptors.push_back(wd);
// Scan subdirectories
DIR* dir = opendir(directory);
if (!dir) {
std::cerr << "Failed to open directory: " << directory << std::endl;
return;
}
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_type == DT_DIR) {
if (std::strcmp(entry->d_name, ".") != 0 && std::strcmp(entry->d_name, "..") != 0) {
std::string subdirectory = std::string(directory) + "/" + entry->d_name;
monitorDirectory(subdirectory.c_str(), fd, watchDescriptors);
}
}
}
closedir(dir);
}
int main() {
int fd = inotify_init();
if (fd < 0) {
std::cerr << "Failed to initialize inotify" << std::endl;
return 1;
}
const char* directory = "/home/wlgfx/Downloads";
std::vector<int> watchDescriptors;
monitorDirectory(directory, fd, watchDescriptors);
std::cout << "Monitoring changes in directory: " << directory << std::endl;
char buffer[EVENT_BUF_LEN];
while (true) {
int length = read(fd, buffer, EVENT_BUF_LEN);
if (length < 0) {
std::cerr << "Failed to read events" << std::endl;
break;
}
int i = 0;
while (i < length) {
struct inotify_event* event = (struct inotify_event*)&buffer[i];
if (event->len) {
if (event->mask & IN_CREATE)
std::cout << "File created: " << event->name << std::endl;
else if (event->mask & IN_DELETE)
std::cout << "File deleted: " << event->name << std::endl;
else if (event->mask & IN_MODIFY)
std::cout << "File modified: " << event->name << std::endl;
else if (event->mask & IN_MOVED_FROM)
std::cout << "File/Folder moved from: " << event->name << std::endl;
else if (event->mask & IN_MOVED_TO)
std::cout << "File/Folder moved to: " << event->name << std::endl;
}
i += EVENT_SIZE + event->len;
}
}
// Cleanup
for (int wd : watchDescriptors)
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
