-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathFileMonitor.cpp
More file actions
84 lines (72 loc) · 2.26 KB
/
Copy pathFileMonitor.cpp
File metadata and controls
84 lines (72 loc) · 2.26 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "FileMonitor.h"
#include "Logger.h"
#include <iostream>
#include <chrono>
FileMonitor::FileMonitor(std::wstring filePath) : filePath_(std::move(filePath)) {
// Start at the end of the file
std::wifstream file(filePath_, std::ios::in);
if (file.is_open()) {
file.seekg(0, std::ios::end);
lastOffset_ = file.tellg();
file.close();
}
}
FileMonitor::~FileMonitor() {
stop();
}
void FileMonitor::start() {
if (running_.exchange(true)) {
return;
}
monitorThread_ = std::thread(&FileMonitor::pollFile, this);
}
void FileMonitor::stop() {
running_ = false;
if (monitorThread_.joinable()) {
monitorThread_.join();
}
}
std::optional<std::deque<std::wstring>> FileMonitor::getNewLines() {
std::lock_guard<std::mutex> lock(linesMutex_);
if (newLines_.empty()) {
return std::nullopt;
}
auto result = std::move(newLines_);
newLines_.clear();
return result;
}
void FileMonitor::pollFile() {
while (running_) {
std::wifstream file(filePath_, std::ios::in);
if (!file.is_open()) {
Logger::logWarning(std::format(L"Failed to open CS2 log: {}", filePath_));
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
continue;
}
// Move to last known offset
file.seekg(lastOffset_, std::ios::beg);
std::deque<std::wstring> tempLines;
std::wstring line;
// Read all new lines from current position
while (std::getline(file, line)) {
if (!line.empty()) {
tempLines.push_back(std::move(line));
}
}
// Update offset to current position
lastOffset_ = file.tellg();
if (lastOffset_ == -1) { // Handle potential EOF or error
file.clear();
file.seekg(0, std::ios::end);
lastOffset_ = file.tellg();
}
if (!tempLines.empty()) {
std::lock_guard<std::mutex> lock(linesMutex_);
newLines_.insert(newLines_.end(),
std::move_iterator(tempLines.begin()),
std::move_iterator(tempLines.end()));
}
file.close();
std::this_thread::sleep_for(std::chrono::milliseconds(50)); // Fast but light
}
}