Editing a text file

  • Hi
    I want to edit a list of text files but my code doesn't work an it's driving me crazy.
    I want to replace all the ' < ' & ' > ' with ' " ' .
    Is there something wrong with this code?

    for (int i=0; i<copiedFiles.count(); ++i)
    QString contents;

        QFile ifile(copiedFiles.at(i));
        if (ifile.open(QIODevice::ReadOnly))
            QTextStream istream(&ifile);
            istream >> contents;
        for (int j=0; j<contents.count(); ++j)
            if (contents[j] == '<' || contents[j] == '>')
        QFile ofile(copiedFiles.at(i));
        if (ofile.open(QIODevice::WriteOnly))
            QTextStream ostream(&ofile);
            ostream << contents;

  • Moderators

    my code doesn't work

    It would be helpful if you said what "doesn't work" means.

    As for the code, istream >> contents; reads only the first word from the file.
    If you want the whole thing use contents = istream.readAll(). Also, you don't need to iterate over every letter. There's a replace() overload that replaces every occurance, so instead of the loop you can just do

    contents.replace(">", "\"");
    contents.replace("<", "\"");

  • Hi thank you chris it worked.
    I wanted to know if this part of code had problem or another part did.

Log in to reply