A more efficient way to monitor a file?

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);
		}
	}



Thanks for any pro tips!

~Newlance
Something like this, perhaps:

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
#include <iostream>
#include <string>
#include <fstream>
#include <thread>
#include <chrono>

int main()
{
    const auto 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
        }
    }
}
closed account (S6k9GNh0)
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...
Last edited on
Topic archived. No new replies allowed.