Originally Posted by
soul_rebel
its really a rather simple thing, i want to preview a textfile by showing its last 5 lines...
is there an easy way i can read the last 5 lines from a file without parsing it entirely? or maybe even clearer: how can i find out how many lines the file has, how can i jump to certain line?
thanks!
I don't know if Qt has a similar function in its QFile class, but in raw file handling you could probably move the cursor of the file to the end with lseek(QFile::handle(), 0, SEEK_END).
Then just keep using lseek and work backwards locating the newlines. Hold on, I'll just check the docs quickly. Yeah, QFile inherits one called seek() that does this. Just it in conjunction with QFile::size() to send the cursor to the end of the file. It's going to be a pain in the ass for you to scan those lines backwards though Have fun. If you really want to do it, I would guess the best bet would be to read the entire file into a string if it's not insanely large, then use
int QString::lastIndexOf ( QChar ch,
int from
= -1, Qt
::CaseSensitivity cs
= Qt
::CaseSensitive ) const
int QString::lastIndexOf ( QChar ch, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
To copy to clipboard, switch view to plain text mode
with '\n' as your QChar and an integer to hold the offset. Make a loop counting down from 4 to 0, and create a QStringList with the last 5 lines using filebuffer.at(offset+1). Remember, if you make the loop count upwards instead of downards, all your strings will be in reverse order.
But no, you can't find out how many lines a file has without reading it. I mean, how else is it going to know how many newlines your file has if it can't scan the entire file and count them all for you? Counting the number of lines is no different from counting the number of times your file contains the letter 'a' or a comma. You can't magically tell without reading the entire file and doing some matching. Unless your text file is like 400000000000000000000000000000000 lines long or it has to be loaded a billion times sequentially, you'll save yourself about half an hour of unnecessary work by just doing it from front to back.
Bookmarks