I am looking to write some code to monitor a file. When it gets written to I would like to read the new lines and act upon them.
So I found this thread: how-to-read-a-growing-text-file-in-c and it shows me how to do this.
However, its a bit of a "polling" approach. Here is the code snippet for convenience. Note: this is not my work (its the answer from the link):
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::ifstream ifs("test.log");
if (ifs.is_open())
{
std::string line;
while (true)
{
while (std::getline(ifs, line)) std::cout << line << "\n";
if (!ifs.eof()) break; // Ensure end of read was EOF.
ifs.clear();
// You may want a sleep in here to avoid
// being a CPU hog.
}
}
return 0;
}
You can see there is the comment: You may want a sleep in here to avoid being a CPU hog.
Is there a way (and there might not be) to wait for the file to be written to, such that some event/condition triggers our thread to wake up? I am thinking along the lines of select()
like function... But I would really like it to be pure c++.
Failing that - is there a non-pure c++ way (for me I require it to work for Linux OS and possibly windows as well)?
I have not written any code yet because I am not even sure where the best place to start is.