(SOLVED) Read everything after an specific keyword



  • Hi everyone,

    I currently write an application using Qt (4.8) and I want to read a specific part of an file. Lets say my file looks like this:

    name = ThisIsAnExampleName

    I now want to read everything whats behind 'name = '. How can I do this?

    ~ jan


  • Moderators

    @jjan

    Hi and welcome to devnet

    It may be a typical job for QRegExp.
    Under the provision that the file size is reasonable, you can reach an entire file in to QString with readall. With QRegExp you can specify what kind of information is relevant for you.

    Or you go through a file line by line and check those.



  • @koahnig

    I have heard about QRegExp and reading a file line by line. Reading file line by line I would do as so

    QFile r_file(fileName);
    if (r_file.open(QIODevice::ReadOnly))
    {
       QTextStream in(&);
       while (!in.atEnd())
       {
          QString line = in.readLine();
       }
       r_file.close();
    }
    

    But I don't know how I get that whats after 'name ='. Can you give me an quick example of how I use readAll() together with QRegExp?


  • Moderators

    @jjan
    you can use indexOf and mid

    QString srch ("name =");
    int pos = line.indexOf(srch);
    if ( pos >= 0 )
    {
         // do something with it 
        QString restOfLine = line.mid (pos + srch.length());
    }
    

    That would be even simpler for your case.

    Note: source not tested. Dump brain to keyboard.



  • @koahnig

    I tried it like so:

    QFile rootFile(*p_path + "/Project.arden");
    if (rootFile.open(QIODevice::ReadOnly))
    {
    	QTextStream in(&rootFile);
    	while (!in.atEnd())
    	{
    		QString line = in.readLine();
    		/* lets get the track name */
    		QString trackName("name = ");
    		int pos = line.indexOf(trackName);
    		if (pos >= 0)
    		{
    			window->setWindowTitle(line);
    		}
    	}
    }
    

    But this doesn't changes the window title (also printf() doesn't works it prints nothing, and also if I use mid()). My file looks like so:

    spec = 0
    includes = LOOKUP_PATHS
    
    [project]
    title = untitled
    author = none
    


  • I fixed it, here is the solution!

    QFile rootFile(*p_path + "/Project.arden");
    				if (rootFile.open(QIODevice::ReadOnly))
    				{
    					QTextStream in(&rootFile);
    					while (!in.atEnd())
    					{
    						QString line = in.readAll();
    						/* lets get the track name */
    						QString trackName("name =");
    						int pos = line.indexOf(trackName);
    						QString theTrackName = line.right(pos + trackName.length());
    						printf(theTrackName.toStdString().c_str());
    					}
    				}
    

  • Moderators

    @jjan
    I guess you have changed also this line to something else

            QString trackName("name = ");
    

    because your file does not contain any "name =" and this cannot be found then.

    ALso you are mixing c and c++ which is possible, but not the prefered way. With Qt typically one uses QDebug for a fast debugging output.

    #include <QDebug>
    
    QFile rootFile(*p_path + "/Project.arden");
    if (rootFile.open(QIODevice::ReadOnly))
    {
          QTextStream in(&rootFile);
          while (!in.atEnd())
          {
                QString line = in.readAll();
               /* lets get the track name */
                QString trackName("name =");
                int pos = line.indexOf(trackName);
                QString theTrackName = line.right(pos + trackName.length());
                // printf(theTrackName.toStdString().c_str());
                qDebug() << theTrackName;
          }
    }
    


  • @koahnig

    The problem now is that it returns not that what I want. However when I change it to name = it gives me everything what behind author = is. Its a bit confusing :/


  • Moderators

    @jjan
    ???

    If you have "name =" the indexOf is exactly searching search for "name =" it cannot match anythingelse. It looks exactly for the same sequence of characters. Also the blanks have to match exactly. Your file contains "spec =", "includes =", "title =" and "author =". Therefore, you have to use those strings for searching. With QRegExp you can gain more flexibility of course. However, this is typically a bit confusing in the beginnng.



  • @koahnig

    What I get is:

     untitled
    author = none
    

    With code:

    QString trackName("title =");
    				            int pos = line.indexOf(trackName);
    				            if (pos >= 0)
    				            {
    					            QString theTrackName = line.mid(pos + trackName.length());
    					            qDebug() << theTrackName;
    				        	}
    

  • Moderators

    @jjan
    This is completely correct with what you wrote in your program.

    QString line = in.readAll();
    

    reads the complete file into the string called line. You are searching for the start of text of "title =" in this complete string. You get a position greater than 0 because the string somewhere later.

    QString theTrackName = line.mid(pos + trackName.length());
    

    will copy the content starting after pos (begin of presence of search string) plus the length of search string. Therefore theTrackName will contain " untitled" followed by the remainder of the content.

    You can replace your readAll (reading the complete file into the string at once) with readLine.
    This should work for your case also.

    When you use Qt creator or another IDE you should use the debugger. This allows you normally to go through the program step by step.
    Further it allows you also to inspect the different vairiables and their actual content after each line.



  • @koahnig

    This worked, many thanks!



  • Hi,

    Is the file you are reading in some sort of settings ini file? If yes, you can use the QSettings class to make things easier and less error-prone.

    Greetings,

    t3685



  • @t3685

    It looks a little bit like an INI but has different style etc, so no its not a settings file ;) But thanks for the info!



  • @koahnig
    Sorry that I am posting here again. My file looks like this:

    window_color_red = 130

    The code to get this is:

    void
    		Theme::loadTheme(QPalette& palette, QApplication& app, Radon::Ui::MainWindow *window)
    		{
    			QString themePath = getTheme();
    			printf(themePath.toStdString().c_str());
    			QFile t(themePath);
    			if (t.open(QIODevice::ReadOnly))
    			{
    				QTextStream input(&t);
    				while (!input.atEnd())
    				{
    					QString line = input.readLine();
    					QString windowRedColorKeyword("window_color_red = ");
    					int redPos = line.indexOf(windowRedColorKeyword);
    					if (redPos >= 0)
    					{
    						QString windowRedColor = line.mid(redPos + windowRedColorKeyword.length());
    						printf(windowRedColor.toStdString().c_str());
    					}
    				}
    			}
    		}
    

    but it don't gives me the number 130, it gives me nothing. Is this basically because it only can read text and not numbers or why?

    EDIT

    This was as mistake I've made, forgot to remove the " in the path!


  • Moderators

    @jjan
    Just for an iteration the code reads line by line. As long as the search text is found, it will provide the remainder of the line. There is real dependency to the content as long as it is displayble (probably also some non-displayable characters). There are some special characters marking the end of lines (line feed (LF) and carriage return (CR) are those at least).



Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.