Sid411
Sid411

Reputation: 703

Config file gets overwritten in qt

I am writing data to a config file using the following code.

   QSettings settings("/root/configFile.ini",QSettings::IniFormat);

   QString userName = lineEditUsername.text();
   QString password = lineEditPassword.text();

   QList<QString> listUsername;
   QList<QString> listPassword;

   settings.beginWriteArray("UserData");

   for(i=0;i<listUsername.size();i++)
  {
      Qstring user = listUsername.at(i);         
      Qstring pass = listPassword.at(i);

      settings.setArryIndex(i);
      settings.setValue("Username",user);
      settings.setValue("Password",pass);
   }

  settings.endArray();
 }

Now when I run the code first time and give 4 or 5 values they are formed in proper order in the file. However if I run the application for second time the values start overwriting from first position. Can some one suggest me some solution for this?

Upvotes: 1

Views: 610

Answers (2)

vahancho
vahancho

Reputation: 21250

Instead of creating and maintaining arrays and indexes, I would propose to create user credentials map and store it in the settings file as follows:

QSettings settings("/root/configFile.ini", QSettings::IniFormat);

QString userName = lineEditUsername.text();
QString password = lineEditPassword.text();

QList<QString> listUsername;
QList<QString> listPassword;

//settings.beginWriteArray("UserData");

QVariantMap userDataMapping;

for(int i = 0; i < listUsername.size() ; i++)
{
    QString user = listUsername.at(i);         
    QString pass = listPassword.at(i);

    userDataMapping[user] = pass;

    //settings.setArryIndex(i);
    //settings.setValue("Username",user);
    //settings.setValue("Password",pass);
}

// Store the mapping.
settings.setValue("UserData", userDataMapping);

//settings.endArray();
// ...

This will store your data in ini file in the following format:

UserData=@Variant(\0\0\0\b\0\0\0\x1\0\0\0\x6\0\x64\0\x64\0\x64\0\0\0\n\0\0\0\x6\0\x62\0\x62\0\x62)

When you read settings, do something like this:

[..]
QVariant v = settings.value("UserData");
QVariantMap map = v.value<QVariantMap>();
QMapIterator<QString, QVariant> i(map);
while (i.hasNext()) {
    i.next();
    QString user = i.key();
    QString pass = i.value().toString();
}

Upvotes: 3

Tim Meyer
Tim Meyer

Reputation: 12600

You need to retrieve the amount of existing entries before adding a new one. Something like this:

int size = settings.beginReadArray( "UserData" );
settings.endArray();

settings.beginWriteArray( "UserData" );
settings.setArrayIndex( size );  // Note: Maybe 'size - 1', not  sure

// ...
settings.endArray();

setArrayIndex( size ) will move the array index to the end and will thus no longer override an existing entry

Upvotes: 0

Related Questions