Unless you have independent information about the structure of the file (such as line lengths), you’ll need either to read the whole file, saving some information until you get to the end, or to read it backwards by using the QFile::size and QFile::seek functions.
If you read the whole file, begin by creating a circular buffer to contain the number of elements before the end (counting the last element) at which you need to start displaying. If the file is random access, you can store the return values of QFile::pos; if the file might not be random access, or if you are confident the files will rarely be large, you can store the contents of the lines themselves (e.g., as QStrings). When you reach the end, use QFile::seek to reposition to the correct location and read the data if you’ve stored positions, or simply display the appropriate elements of the buffer if you’ve stored data.
To read backwards, pick a sensible buffer size (in this case you’ll be buffering bytes, not positions or QStrings), then QFile::seek to QFile::size minus the buffer size. Read into the buffer using QFile::readData and parse it yourself for line endings. Remember that the first line in the buffer is not necessarily complete! If you have enough lines, display them; if not, seek buffer size bytes earlier than before (but not to a position less than zero), allocate, read and parse another buffer, and so on.





Reply With Quote
Bookmarks