Home > Enterprise >  How to write contents into a file in multiple steps?
How to write contents into a file in multiple steps?

Time:11-16

I have a basic question:

I opened an old log file in the readonly mode and stored content in QTextStream, and closed it. It basically contains 7 lines of texts.

I opened another file to write and tried to read line by line. I can read line by line and write entire content into the new file. But I'm trying to do the follwoing:

Write first 5 lines as it is to the new file do some change to Line 6 and 7 and write to the new line

    QString oldfilename = "log_file";
    QString newfilename = "new_log_file";

    QString path1 = QCoreApplication::applicationDirPath() "/" oldfilename  ".txt";
    QString path2 = QCoreApplication::applicationDirPath() "/" newfilename ".txt";

    QFile readfile(path1);
    if(!readfile.open(QIODevice::ReadOnly | QIODevice::Text)){

        qDebug() << "Error opening file: "<<readfile.errorString();
    }

    QTextStream instream(& readfile);
 


    QFile writefile(path2);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        int nb_line(0);
        while(!instream.atEnd())
        {
            QString line = instream.readLine();


// Here I need to write first five lines of the file as it is 


            
           if(nb_line == 6 )
            {

             // Do some manipulation here

               outstream <line_6<< '\n'

            }
            if(nb_line == 7 )
            {
                

              // Do some manipulation here

               outstream <line_7<< '\n'

            }
            
          nb_line;
       
          }

        

   readfile.close();
     
   writefile.close();
    }

Can some one suggest an efficient way (using loops) to select first lines as it is and to manage changes to line 6 and 7

I can write whole contents line by line into the new file but not sure how to use right loops to select

for example if the contents of the old file is

Apple
Cherry
Pineapple
Pear
Grape
Mushroom
Egg

I need my new file as:

Apple
Cherry
Pineapple
Pear
Grape
Orange
Watermelone

CodePudding user response:

since it is 5 lines you could write a simple while loop (I am using the fstream library)

void readFirstFiveLines() {
    std::ifstream file("file.txt");
    std::ofstream file2("file2.txt");
    std::string line;
    int i = 0;
    while (std::getline(file, line) && i < 5) {
        file2 << line << std::endl;
        i  ;
    }
}
  •  Tags:  
  • c qt
  • Related