Nominate our 2022 Qt Champions!

Rewrite specific string in file

  • Hey,
    I currently try to write a little configuration "parser" for myself. I want to overwrite an existing value. The INI file looks like this:

    test = abc123

    I have tried it with this:

    void INIHelper::writeValue(QString& file_path, QString& property, QString value)
    	QFileInfo check(file_path);
    	if (!check.exists())
    		// We have no configuration file. Lets contact ConfigurationWriter to initialize one.
    		// TODO(15.10.2015, jan): Write configuration file.
    		QFile f(file_path);
    		if ( QIODevice::Append ))
    			QTextStream inw(&f);
    			while (!inw.atEnd())
    				QString l = inw.readLine();
    				QString _property(property + " = ");
    				int propertyPos = l.indexOf(_property);
    				if (propertyPos >= 0)
    				{ // we are now behind 'test = '
    					QString old_value = l.mid(propertyPos + _property.length());
    					// old_value is the value of test!
    					old_value = value;
    					inw << old_value << endl;

    And I test it with:

      QString path("c://users//jan//desktop//test.ini");
      QString prop2("test");
      QString ret_test = ini_h->getValue(path, prop2);
      ini_h->writeValue(path, prop2, "testststst");

    But this doesn't works, nothing changes there. If I set a breakpoint on ret_test I get test (or better test =) back, so its a problem at rewriting the value to the file. How can I make this work?


  • Moderators


    Why not use QSettings?

    Anyway, if you want to implement this yourself, you first need to learn about file pointers and how to read and write to the same file at the same time:

Log in to reply