You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
1.5 KiB
54 lines
1.5 KiB
#include "file_monitor.h"
|
|
#include <fstream>
|
|
#include <thread>
|
|
#include <sstream>
|
|
|
|
FileMonitor::FileMonitor(const std::string& root_path, FileCallback callback)
|
|
: root_path_(root_path), callback_(std::move(callback)) {}
|
|
|
|
FileMonitor::~FileMonitor() {
|
|
stop();
|
|
}
|
|
|
|
void FileMonitor::start() {
|
|
running_ = true;
|
|
monitor_thread_ = std::thread(&FileMonitor::monitor_thread, this);
|
|
}
|
|
|
|
void FileMonitor::stop() {
|
|
running_ = false;
|
|
if (monitor_thread_.joinable()) {
|
|
monitor_thread_.join();
|
|
}
|
|
}
|
|
|
|
void FileMonitor::monitor_thread() {
|
|
while (running_) {
|
|
scan_directory(root_path_);
|
|
std::this_thread::sleep_for(std::chrono::seconds(1));
|
|
}
|
|
}
|
|
|
|
void FileMonitor::scan_directory(const fs::path& dir) {
|
|
for (const auto& entry : fs::recursive_directory_iterator(dir)) {
|
|
if (!entry.is_regular_file()) continue;
|
|
|
|
const auto& path = entry.path();
|
|
auto last_write_time = fs::last_write_time(path);
|
|
|
|
// 检查文件是否被修改
|
|
auto it = file_times_.find(path.string());
|
|
if (it == file_times_.end() || it->second != last_write_time) {
|
|
std::string content = read_file_content(path);
|
|
callback_(path.string(), content);
|
|
file_times_[path.string()] = last_write_time;
|
|
}
|
|
}
|
|
}
|
|
|
|
std::string FileMonitor::read_file_content(const fs::path& path) {
|
|
std::ifstream file(path, std::ios::binary);
|
|
std::stringstream buffer;
|
|
buffer << file.rdbuf();
|
|
return buffer.str();
|
|
}
|