I have a program that is now working. it reads from a log file and acts according to what was read. once it has reached the end of the file (when peek=-1) it closes the file, reopens it, skips over all that has been previously read(using a counter) and checks for new material. It works very well, however it consumes nearly 15% of my CPU! Is there a better way to do THIS:
1 2 3 4 5 6 7 8 9 10 11
while(inputFile.peek() == -1) // Checks for end of file flag
{
inputFile.close();
inputFile.open(fileLoc.c_str());
for(int i=0;i<linesRead;i++) //reads linesRead but does not
{ //do anything with this info.
//is there abetter way to skip lines?
getline(inputFile, stringHolder);
}
}
#include <iostream>
#include <string>
#include <fstream>
#include <thread>
#include <chrono>
int main()
{
constauto pause_period = std::chrono::seconds(5) ; // 5 seconds
std::ifstream log_file( "my_logfile.log" ) ;
while(log_file)
{
std::string line ;
// keep getting lines one by one till getline() fails
while( std::getline( log_file, line ) )
{
// process the line that was read
std::cout << line << '\n' ;
}
// if getline failed because eof was reached (nothing more to read right now)
if( log_file.eof() )
{
log_file.clear() ; // clear the error state
// wait for pause_period (five seconds in this example)
std::this_thread::sleep_for( pause_period ) ;
// and try to read more lines
}
}
}
A more effecient method would be to ask the OS for file system changes concerning that file rather than actively looking for it. Might be an abstract library out there somewhere but I've done this before on linux using inotify.
Alternatively, you can look at the files metadata for when it was last changed. If it's newer, then read it.
I would look into libuv. Quite an interesting library...