Repo-Init
 
Loading...
Searching...
No Matches
FileHelpers.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <atomic>
4#include <filesystem>
5#include <fstream>
6#include <regex>
7#include <string>
8#include <sys/inotify.h>
9#include <thread>
10#include <vector>
11
19inline std::vector<std::string> findFromFile(const std::string &filePath, const std::string &pattern,
20 std::string &lastWord)
21{
22 const std::regex regExp(pattern);
23 std::ifstream inFile(filePath);
24 std::vector<std::string> matchedLines;
25
26 std::string readLine;
27 while (getline(inFile, readLine))
28 {
29 if (std::regex_search(readLine, regExp))
30 {
31 matchedLines.push_back(readLine);
32 }
33 }
34
35 if (!matchedLines.empty())
36 {
37 auto pos = matchedLines.front().find_last_of(' ');
38 if (pos != std::string::npos && pos != matchedLines.front().size())
39 {
40 lastWord = matchedLines.front().substr(pos + 1);
41 }
42 }
43
44 return matchedLines;
45}
46
53inline std::vector<std::string> findFromFile(const std::string &filePath, const std::string &pattern)
54{
55 std::string lastWord;
56 return findFromFile(filePath, pattern, lastWord);
57}
58
60using FNotifyCallback = std::function<void(const void *)>;
61
66 private:
68 int _fDescriptor{-1};
70 int _wDescriptor{-1};
72 std::filesystem::path _filePath;
76 uint32_t _notifyEvents;
78 const void *_userPtr = nullptr;
79
81 std::unique_ptr<std::thread> _thread;
83 std::atomic_flag _shouldStop{false};
84
85 void threadFunc() const noexcept;
86
87 public:
93 explicit FileMonitor(std::filesystem::path filePath, uint32_t notifyEvents = IN_MODIFY);
94
96 FileMonitor(const FileMonitor & /*unused*/) = delete;
97
99 FileMonitor(FileMonitor && /*unused*/) = delete;
100
102 FileMonitor &operator=(FileMonitor /*unused*/) = delete;
103
105 FileMonitor &operator=(FileMonitor && /*unused*/) = delete;
106
107 [[nodiscard]] FNotifyCallback notifyCallback() const { return _notifyCallback; }
108 void notifyCallback(FNotifyCallback func) { _notifyCallback = std::move(func); }
109
114 void userPtr(const void *ptr) { _userPtr = ptr; }
115
119 ~FileMonitor();
120};
std::function< void(const void *)> FNotifyCallback
Callback function for file notifications.
std::vector< std::string > findFromFile(const std::string &filePath, const std::string &pattern, std::string &lastWord)
const void * _userPtr
User pointer.
FNotifyCallback _notifyCallback
Callback function.
int _fDescriptor
File descriptor.
void threadFunc() const noexcept
void notifyCallback(FNotifyCallback func)
std::atomic_flag _shouldStop
Flag to stop monitoring.
std::unique_ptr< std::thread > _thread
Thread.
void userPtr(const void *ptr)
FNotifyCallback notifyCallback() const
int _wDescriptor
Watch descriptor.
uint32_t _notifyEvents
Notify types.
std::filesystem::path _filePath
File path.