2015-08-24 983 views
1

我想讀取逗號分隔數據形式的INI文件。我已經在這裏讀到:QSettings:如何從INI文件中讀取數組

...那個逗號作爲分隔符和QSettings價值函數將返回QStringList中處理。

然而,我在INI文件中的數據是這樣的:

norm-factor=<<eof 
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0 
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0 
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0 
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0 
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0 
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0 
eof 

我不需要整個矩陣。所有排在一起對我來說都是公平的。但QSettings可以處理這樣的結構嗎?

我應該閱讀使用:

QStringList norms = ini->value("norm-factor", QStringList()).toStringList(); 

還是我必須分析它以另一種方式?

+3

你試過了嗎?爲什麼不? –

+1

您能否提供一個完整的示例,以便我們可以運行和修改它?這聽起來像你沒有按照你的建議打開它。嘗試一下。 –

+1

它不是標準的ini格式(對於Qt)。可能,你不能用'QSettings'來閱讀。 –

回答

2

換行符是一個問題,因爲INI文件爲自己的語法使用換行符。 Qt似乎不支持你的類型的續行(<<eol ... eol)。

QSettings s("./inifile", QSettings::IniFormat); 
qDebug() << s.value("norm-factor"); 

產生

QVariant(QString, "<<eof") 

<<eol表達可能是無效的INI本身。 (Wikipedia on INI files

我建議你手動解析文件。

+0

這就是我所害怕的,謝謝 – Michal

+0

請考慮接受/覈對答案並提高它。 –

2

羅尼布倫德爾的答案是正確的......我只是添加代碼,上面的問題解決了...它創建了糾正陣列臨時INI文件:

/** 
* @param src source INI file 
* @param dst destination (fixed) INI file 
*/ 
void fixINI(const QString &src, const QString &dst) const { 

    // Opens source and destination files 
    QFile fsrc(src); 
    QFile fdst(dst); 
    if (!fsrc.open(QIODevice::ReadOnly)) { 
    QString msg("Cannot open '" + src + "'' file."); 
    throw new Exception(NULL, msg, this, __FUNCTION__, __LINE__); 
    } 
    if (!fdst.open(QIODevice::WriteOnly)) { 
    QString msg("Cannot open '" + dst + "'' file."); 
    throw new Exception(NULL, msg, this, __FUNCTION__, __LINE__); 
    } 

    // Stream 
    QTextStream in(&fsrc); 
    QTextStream out(&fdst); 

    bool arrayMode = false; 
    QString cache; 
    while (!in.atEnd()) { 

    // Read current line 
    QString line = in.readLine(); 

    // Enables array mode 
    // NOTE: Clear cache and store 'key=' to it, without '<<eof' text 
    if (arrayMode == false && line.contains("<<eof")) { 
     arrayMode = true; 
     cache = line.remove("<<eof").trimmed(); 
     continue; 
    } 

    // Disables array mode 
    // NOTE: Flush cache into output and remove last ',' separator 
    if (arrayMode == true && line.trimmed().compare("eof") == 0) { 
     arrayMode = false; 
     out << cache.left(cache.length() - 1) << "\n"; 
     continue; 
    } 

    // Store line into cache or copy it to output 
    if (arrayMode) { 
     cache += line.trimmed() + ","; 
    } else { 
     out << line << "\n"; 
    } 
    } 
    fsrc.close(); 
    fdst.close(); 
}