Watching for file changes can vary significantly between platforms. Below are some methods to watch for file changes in C++ on different operating systems, including Windows and Linux.
// Example - Monitoring file changes in Windows
#include <windows.h>
#include <stdio.h>
void WatchFile(const char* filename) {
HANDLE hDir = CreateFile(
filename,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
NULL
);
if (hDir == INVALID_HANDLE_VALUE) {
printf("Could not open directory: %lu\n", GetLastError());
return;
}
FILE_NOTIFY_INFORMATION buffer[1024];
DWORD bytesReturned;
while (true) {
if (ReadDirectoryChangesW(
hDir,
&buffer,
sizeof(buffer),
FALSE,
FILE_NOTIFY_CHANGE_LAST_WRITE,
&bytesReturned,
NULL,
NULL
)) {
printf("File changed!\n");
}
}
CloseHandle(hDir);
}
// Example call
// WatchFile("C:\\path\\to\\your\\file.txt");
// Example - Monitoring file changes in Linux
#include <sys/inotify.h>
#include <limits.h>
#include <stdio.h>
void WatchFile(const char* filename) {
int fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return;
}
int wd = inotify_add_watch(fd, filename, IN_MODIFY);
if (wd < 0) {
perror("inotify_add_watch");
return;
}
char buffer[sizeof(struct inotify_event) + NAME_MAX + 1];
while (true) {
int length = read(fd, buffer, sizeof(buffer));
if (length < 0) {
perror("read");
return;
}
struct inotify_event* event = (struct inotify_event*)&buffer[0];
if (event->mask & IN_MODIFY) {
printf("File modified: %s\n", event->name);
}
}
inotify_rm_watch(fd, wd);
close(fd);
}
// Example call
// WatchFile("/path/to/your/file.txt");
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?