软件开发过程中经常会用到配置文件,某些应用场景要求在软件运行时动态修改配置文件,此时就需要监控配置文件是否被修改,下面我们就来看看如何使用C++实现这一功能吧
软件开发过程中经常会用到配置文件,某些应用场景要求在软件运行时动态修改配置文件,此时就需要监控配置文件是否被修改,如果修改了,重新加载。
FileWatcher.h
#ifndef FILEWATCHER_H
#define FILEWATCHER_H#include <ctime>
#include <chrono>
#include <string>
#include <thread>
#include <atomic>typedef std::chrono::system_clock Clock;
typedef std::chrono::duration<long long, std::micro> Duration;
typedef std::chrono::time_point<Clock, Duration> Time;template <typename FromDuration>
inline Time time_cast (std::chrono::time_point<Clock, FromDuration> const & tp)
{return std::chrono::time_point_cast<Duration, Clock> (tp);
}inline Time now ()
{return time_cast(Clock::now ());
}inline Time from_time_t (time_t t_time)
{return time_cast(Clock::from_time_t (t_time));
}struct FileInfo
{Time mtime;off_t size;
};class FileWatcher
{
public:FileWatcher(const std::string& file, unsigned int millis);~FileWatcher();protected:void run();private:bool checkForFileModification();void updateLastModInfo();bool getFileInfo(FileInfo *fi, const std::string &name);private:FileInfo m_lastFileInfo;std::string m_file;unsigned int const m_waitMillis;std::atomic_bool m_stopped;std::thread m_thread;
};#endif // FILEWATCHER_H
FileWatcher.cpp
#include "FileWatcher.h"
#include "tchar.h"
#include "iostream"FileWatcher::FileWatcher(const std::string& file, unsigned int millis): m_file(file), m_waitMillis(millis), m_stopped(false), m_thread(&FileWatcher::run, this)
{m_lastFileInfo.mtime = time_cast(Clock::now ());m_lastFileInfo.size = 0;updateLastModInfo();
}FileWatcher::~FileWatcher()
{m_stopped = true;if (m_thread.joinable()){m_thread.join();}
}void FileWatcher::run()
{while (!m_stopped){bool modified = checkForFileModification();if(modified){updateLastModInfo();std::cout << "File changed" << std::endl;}std::this_thread::sleep_for(std::chrono::milliseconds(m_waitMillis));}
}bool FileWatcher::checkForFileModification()
{FileInfo fi;if (!getFileInfo(&fi, m_file) ){return false;}bool modified = fi.mtime > m_lastFileInfo.mtime|| fi.size != m_lastFileInfo.size;return modified;
}void FileWatcher::updateLastModInfo()
{FileInfo fi;if (getFileInfo(&fi, m_file)){m_lastFileInfo = fi;}
}bool FileWatcher::getFileInfo(FileInfo *fi, const std::string &name)
{struct _stat fileStatus;if (_stat(name.c_str (), &fileStatus) == -1){return false;}fi->mtime = from_time_t(fileStatus.st_mtime);fi->size = fileStatus.st_size;return true;
}
main.cpp
#include "FileWatcher.h"#include <iostream>int main(int argc, char *argv[])
{char filePath[1024] = {0};// 获取绝对路径._fullpath(filePath, "config.txt", 1024);std::cout <<filePath << std::endl;FileWatcher fw(filePath, 1000);system("pause");return 0;
}
这里config.txt和可执行文件同一目录,每次修改config.txt,就会打印File changed