How do I watch for file changes (platform-specific)?

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.

Keywords: C++, file monitoring, platform-specific, Windows, Linux, inotify, ReadDirectoryChangesW, file changes
Description: This guide provides methods for monitoring file changes in C++, utilizing platform-specific APIs like inotify for Linux and ReadDirectoryChangesW for Windows.

// 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");
    

Keywords: C++ file monitoring platform-specific Windows Linux inotify ReadDirectoryChangesW file changes