Reading a Log File in Reverse
Greetings. I'm a first time poster but a long time anonymous coward to this board.
I'm a bit stuck on this rather simple task. For my current program which analyzes log files, I need to read lines at a time from the files. These files can range in a few megabytes to several gigabytes in size. I can't read the entire file into memory, so I have to scan in lines from the end of the file and work my way up until I've hit a certain date range (which is beyond the scope of this thread).
My problem is that I know how to read a file in the standard way -- beginning to end -- but how is this done in reverse?
Here is a snippet of where I am. It outputs nothing though. My thoughts were that it should scan from the end of the file backwards but it appears to advance the pointer when reading a character.
Code:
ifstream infile(logfilepath);
string strLine;
char szBuf;
ifstream::pos_type posBeg = infile.tellg();
infile.seekg(0, ios_base::end);
ifstream::pos_type posCur = infile.tellg();
while (posCur != posBeg)
{
cout << infile.get() << endl;
posCur -= 2;
infile.seekg(posCur);
}
infile.close();
I've done this sort of thing many times with Perl, PHP, Python, and Bash but I'm baffled by how mysterious it is to do it in C++. I've tried Googling for some approaches but they all lead to reading the entire file into an STL container and using a reverse iterator, which is out of the question with such large log files in this case.
Any help would be greatly appreciated. It's been many years since I've done any large projects with C or C++ so I'm a bit rusty.
This program is targeted for Linux, so it has to avoid any Win32/MFC-specific calls.