Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Solved Editing a text file

    General and Desktop
    2
    3
    1242
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • S
      shahriar25 last edited by

      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;
          }
          ifile.close();
      
          for (int j=0; j<contents.count(); ++j)
          {
              if (contents[j] == '<' || contents[j] == '>')
              {
                  contents.replace(j,1,QChar('\"'));
              }
          }
      
          QFile ofile(copiedFiles.at(i));
          if (ofile.open(QIODevice::WriteOnly))
          {
              QTextStream ostream(&ofile);
      
              ostream << contents;
          }
          ofile.close();
      }
      
      1 Reply Last reply Reply Quote 0
      • Chris Kawa
        Chris Kawa Moderators last edited by

        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("<", "\"");
        
        1 Reply Last reply Reply Quote 1
        • S
          shahriar25 last edited by

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

          1 Reply Last reply Reply Quote 0
          • First post
            Last post