使用Qt替换C ++中的文本中的文本

时间:2015-06-26 09:16:59

标签: c++ qt io

我正在使用Qt库,我正在尝试更改文件的内容。我想用fname替换存储在tok2中的文本。 更新的代码:

QFile file(destPath);
if (file.open(QIODevice::ReadWrite | QIODevice::Text))
{
  QTextStream stream(&file);
  while (!stream.atEnd())
  {
    QString line = stream.readLine();
    QStringList tokenList = line.split("\t");        
    if ( tokenList.count() == 2 && (tokenList.at(0).endsWith("FILE",Qt::CaseInsensitive)))
    {   
      QString tok1 = tokenList.at(0).trimmed();    
      QString tok2 = tokenList.at(1).trimmed();
      QFileInfo relPath(tok2);
      QString fname = relPath.fileName();

        QString newLine = tok1.append(" ").append(fname);
        QString oldLine = tok1.append(" ").append(tok2);
        qDebug() << "Original line: " << oldLine << "New line" << newLine;
        QTextStream in(&file);

        while (!in.atEnd())
        {
          QString line = in.readLine();
          QString outline = line.replace(QString(oldLine), QString(newLine));
          in << outline;
        }
      }
    }                       
  }
}

tok2的原始内容格式为../something/filename.ext,我必须用filename.ext替换它,但上面的代码不是用fname替换tok2的内容,总之我无法写入文件。

2 个答案:

答案 0 :(得分:4)

You are making things too complicated.

const QString doStuff(const QString &str)
{
    // Change string however you want
}

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

    const QString filePath = "/home/user/test.txt";
    QTextCodec *codec = QTextCodec::codecForLocale();

    // Read file
    QFile file(filePath);
    if (!file.open(QFile::ReadOnly)) {
        qDebug() << "Error opening for read: " << file.errorString();
        return -1;
    }
    QString text = codec->toUnicode(file.readAll());
    file.close();

    text = doStuff(text);

    // Write file
    if (!file.open(QFile::WriteOnly)) {
        qDebug() << "Error opening for write: " << file.errorString();
        return -2;
    }
    file.write(codec->fromUnicode(text));
    file.close();

    return 0;
}

Works fast enough, if your file size is less then the amount of your RAM.

答案 1 :(得分:1)

我的解决方案对我来说非常有用:

// Open file to copy contents
QFile file(srcPath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
    // Open new file to write
    QFile temp(destPath);
    if (temp.open(QIODevice::ReadWrite | QIODevice::Text))
    {
          QTextStream stream(&file);
          QTextStream out(&temp);
          while (!stream.atEnd())
          {
                QString newLine;
                //do stuff
                out << newLine  << "\n";
          }
      temp.close();
     }
     file.close();
 }