2017-03-07 64 views
0

我是初學者到C++和qt兩者。在qt中讀取Qfile

我必須閱讀用戶配置文件並在添加新用戶時對其進行更改。

[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 

我試過簡單的cpp文件來閱讀它如下。

#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; 
    } 

任何建議,如何才能讓特定的用戶(在[「用戶」])出現在文件中,這樣我就可以重寫它的領域,否則創建另一個字符串。

我附上enter image description here輸出屏幕截圖

回答

1

我想你可以使用QSettings類改爲「INI文件」直接,不需要解析自己的內容。

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

感謝它的工作.. – zodango