ThomasMonkman / filewatch

File watcher in c++
MIT License
426 stars 70 forks source link

Filewatch

Branch Status
Master Master

Single header folder/file watcher in C++11 for windows and linux, with optional regex filtering

Install:

Drop FileWatch.hpp in to your include path, and you should be good to go.

Compiler Support:

Works on:

Examples:

On linux or none unicode windows change std::wstring for std::string or std::filesystem (boost should work as well).

Simple:
filewatch::FileWatch<std::wstring> watch(
    L"C:/Users/User/Desktop/Watch/Test"s, 
    [](const std::wstring& path, const filewatch::Event change_type) {
        std::wcout << path << L"\n";
    }
);
Change Type:
filewatch::FileWatch<std::wstring> watch(
    L"C:/Users/User/Desktop/Watch/Test"s, 
    [](const std::wstring& path, const filewatch::Event change_type) {
        std::wcout << path << L" : ";
        switch (change_type)
        {
        case filewatch::Event::added:
            std::cout << "The file was added to the directory." << '\n';
            break;
        case filewatch::Event::removed:
            std::cout << "The file was removed from the directory." << '\n';
            break;
        case filewatch::Event::modified:
            std::cout << "The file was modified. This can be a change in the time stamp or attributes." << '\n';
            break;
        case filewatch::Event::renamed_old:
            std::cout << "The file was renamed and this is the old name." << '\n';
            break;
        case filewatch::ChangeType::renamed_new:
            std::cout << "The file was renamed and this is the new name." << '\n';
            break;
        };
    }
);
Regex:

Using the standard regex libary you can filter the file paths that will trigger. When using wstring you will have to use std::wregex

filewatch::FileWatch<std::wstring> watch(
    L"C:/Users/User/Desktop/Watch/Test"s,
    std::wregex(L"test.*"),
    [](const std::wstring& path, const filewatch::Event change_type) {
        std::wcout << path << L"\n";
    }
);
Using std::filesystem:
filewatch::FileWatch<std::filesystem::path> watch(
    L"C:/Users/User/Desktop/Watch/Test"s, 
    [](const std::filesystem::path& path, const filewatch::Event change_type) {
        std::wcout << std::filesystem::absolute(path) << L"\n";     
    }
);
Works with relative paths:
filewatch::FileWatch<std::filesystem::path> watch(
    L"./"s, 
    [](const std::filesystem::path& path, const filewatch::Event change_type) {
        std::wcout << std::filesystem::absolute(path) << L"\n";     
    }
);
Single file watch:
filewatch::FileWatch<std::wstring> watch(
    L"./test.txt"s, 
    [](const std::wstring& path, const filewatch::Event change_type) {
        std::wcout << path << L"\n";        
    }
);