-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFileWatcher.cpp
More file actions
68 lines (61 loc) · 1.62 KB
/
FileWatcher.cpp
File metadata and controls
68 lines (61 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "pch.h"
#include "FileWatcher.h"
std::optional<FILETIME> FileWatcher::MyFileTime()
{
HANDLE hFile = CreateFileW(m_path.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
std::optional<FILETIME> result;
if (hFile != INVALID_HANDLE_VALUE)
{
FILETIME lastWrite;
if (GetFileTime(hFile, nullptr, nullptr, &lastWrite))
{
result = lastWrite;
}
CloseHandle(hFile);
}
return result;
}
void FileWatcher::Run()
{
while (1)
{
auto lastWrite = MyFileTime();
if (!m_lastWrite.has_value())
{
m_lastWrite = lastWrite;
}
else if (lastWrite.has_value())
{
if (m_lastWrite->dwHighDateTime != lastWrite->dwHighDateTime ||
m_lastWrite->dwLowDateTime != lastWrite->dwLowDateTime)
{
m_lastWrite = lastWrite;
m_callback();
}
}
if (WaitForSingleObject(m_abortEvent, m_refreshPeriod) == WAIT_OBJECT_0)
{
return;
}
}
}
FileWatcher::FileWatcher(const std::wstring& path, std::function<void()> callback, DWORD refreshPeriod) :
m_refreshPeriod(refreshPeriod),
m_path(path),
m_callback(callback)
{
m_abortEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (m_abortEvent)
{
m_thread = std::thread([this]() { Run(); });
}
}
FileWatcher::~FileWatcher()
{
if (m_abortEvent)
{
SetEvent(m_abortEvent);
m_thread.join();
CloseHandle(m_abortEvent);
}
}