wazza
wazza

Reputation: 317

Replacing a text in file in C++ using Qt

I am using Qt Library and i am trying to change the contents of a file. I want to replace the text stored in tok2 by fname. Updated Code:

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

Original contents of tok2 are in format ../something/filename.ext and i have to replace it by filename.ext but above code is not replacing the contents of tok2 by fname, in short i am unable to write in this file.

Upvotes: 1

Views: 2444

Answers (2)

wazza
wazza

Reputation: 317

My solution which worked perfectly for me:

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

Upvotes: 1

Amartel
Amartel

Reputation: 4286

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.

Upvotes: 4

Related Questions