Get single line from QFile
-
Hi,
I would like to read a single line at position 5 from the QFile object and write it to QString. How could I do that?
-
@jsulm I wrote this code to get 2 line from below file
file.txt
abcdef ghijkl mnoprs tuvwxy
My code:
file.seek(2); QByteArray line = file.readLine(); qDebug()<< QString(line);
But my output is:
cdef
What could I do to get below line?
mnoprs
-
@Creatorczyk question, do you know, the exact length of your each line ? And do you know the end of line format ?
If the answer is yes, then you simply used seek false.
seek about = bytes in line * 2 to get to the start of line 3
if you don't know it, or it may vary, you'll have to use
https://doc.qt.io/qt-5/qiodevice.html#readLine-1and count how often you read a line, discard everything before the count of 3
-
@Creatorczyk seek() works with bytes, not lines. In your first post you did not say that "position 5" means line 5 and not byte 5. If you want to get the line number n you have to read and skip lines 0..n-1:
for (int i = 0; i < 2; ++i) file.readLine(); QString line = file.readLine();
Keep in mind: this code does not have any error handling (you could have less lines in the file than you expect).