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

Replacing a text in file in C++ using Qt

本文关键字:文本 文件 中文 Qt 替换 C++ 使用      更新时间:2023-10-16

我正在使用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.eext替换它,但上面的代码并没有用fname替换tok2的内容,简而言之,我无法在这个文件中写入。

你把事情搞得太复杂了。

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

如果您的文件大小小于RAM的大小,则工作速度足够快。

我的解决方案非常适合我:

// 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();
 }