简体   繁体   中英

read Qfile in qt

I am beginner to c++ and qt both.

I have to read user configuration file and changes to it when new user get added.

[db-Host]
type=1
host=10.25.36.15
charsize=0
foreground=0
background=0
Cursor=0
AnswerBack=None
CursorKeypad=0
termtype=vt220
capslock=0
CharacterSet=0
Num Lock=0
maxrows=0
maxcols=0
Cser_connec=0
functionkey_set=0
mouseCursor=1
autoStart=1
euro=0

i have tried simple cpp file to read it as follow.

#include "mainwindow.h"
#include <QApplication>
#include<QFile>
#include<QString>

#include <QTextStream>

QTextStream cout(stdout);
QTextStream cerr(stderr);



int main(int argc, char *argv[])
{

    QString str, newstr;
    QTextStream strbuf(&str);

    QString useName = "[db-Host]";
    QString pi = "ServerName=55333";

    cout << "An in-memory stream" << endl;
    strbuf << "userName: " << lucky << endl
    << "pi: " << pi << endl;


    QFile data("/home/sidheshwar/Desktop/temp.txt");


    cout << "Read data from the file - watch for errors." << endl;
    if(data.open( QIODevice ::ReadOnly)) {
    QTextStream in(&data);
    QString lucky2;
    in >> newstr >> lucky2>>endl;
    if (lucky != lucky2)
    cerr << "ERROR! wrong " << newstr << lucky2 << endl;
    else
    cout << newstr << " OK" << endl;
    QString pi2;
    in >> newstr >> pi2;
    if (pi2 != pi)
    cerr << "ERROR! Wrong " << newstr << pi2 << endl;
    else
    cout << newstr << " OK" << endl;

    data.close();
    }

    return 0;
    }

Any suggestion how can get specific user (in ["user"]) present in file so i can rewrite its field otherwise create another strings.

i have attached enter image description here output screen shot

I think you can use the QSettings class to read "ini files" directly, no need to parse the content yourself.

QSettings settings("/home/sidheshwar/Desktop/temp.txt", QSettings::IniFormat);
// read the [db-Host] host value
QString host = settings.value("db-Host/host").toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM