QSettings:如何从INI文件中读取数组

QSettings: How to read array from INI file

本文关键字:文件 读取 数组 INI QSettings      更新时间:2023-10-16

我想读取逗号分隔的数据形式INI文件。我已经读过了:

  • QSettings::IniFormat带有","返回QStringList
  • 如果值包含逗号字符,如何使用QSetting读取值

…逗号被当作分隔符,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();

或者我必须以另一种方式解析它?

换行是一个问题,因为INI文件在自己的语法中使用换行。Qt似乎不支持您的类型的行延续(<<eol ... eol)。

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

QVariant(QString, "<<eof")

<<eol表达式本身可能是无效的INI。(维基百科INI文件)

Ronny Brendel的答案是正确的…我只是添加代码,解决上述问题…它创建了一个临时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();
}