PDA

View Full Version : Read a specific line from a file



rleojoseph
21st March 2011, 07:23
I need to read a specific line from my file.

My file contains these contents


<html > one </html>
<html > two </html>
<html> three</html>


I know to read the entire file using QFile,QTextStream.
But now i want to read the file which starts with <html>. Even if i use readLine() , i can read each and every line of a File. Does anybody know how to read particular line from a File ??????????

squidge
21st March 2011, 07:54
Yes, read all the lines previous to the line you want and ignore them, then read the line you want and store it. If the lines are the same length then you can seek to a particular position in the file using a simple formula, but they rarely are.

But if your reading xml (it seems like it from your example), a better idea would be QDomDocument.

mcosta
21st March 2011, 07:56
If your file has XML like contents, you can use QXmlStreamReader or QDomDocument.

If your file is a flat file (as you described) you can only implement this feature by hands

rleojoseph
21st March 2011, 08:14
What about reading a particular Line from a Text file ??????????

FelixB
21st March 2011, 08:19
what does "particular" mean? The n-th line? A line starting with "xyz"?

rleojoseph
21st March 2011, 08:49
ya!! A line starts with "abc " like that!!

FelixB
21st March 2011, 09:07
then you read line by line. you check each line if it starts with "abc" and if it does, you end the loop.

mcosta
21st March 2011, 09:07
The easiest way to read a Text File is using QTextStream.

You can create a class that inherit from it and add this function.
Example


class MyTextStream: public QTextStream
{
....
public:
QString readLineStartingWith ( const QString& str, qint64 maxlen = 0 );
};

wysota
21st March 2011, 10:15
The easiest way to read a Text File is using QTextStream.
No, that's not the easiest way. Especially for a total noob in the topic like the OP.

@rleojoseph:
Use readLine() together with QString::startsWith()

mcosta
21st March 2011, 11:41
@rleojoseph:
Use readLine() together with QString::startsWith()

I agree with you. I suggested a dedicated class if the task of reading line with specific start is common and repeated in his code

wysota
21st March 2011, 11:46
After sticking here for a couple of years I became acustomed to the fact that newbies don't want/don't know how to subclass. It's an apparent lack of object oriented programming skills but there is nothing we can do about it apart repeating over and over to learn C++ before using Qt.

mcosta
21st March 2011, 11:58
I should suggest us to highlight to newbies that a good Qt developer needs to be a good C++ developer