0

I'm a bit stuck in opening a file and modify it in Qt. I have got a file that has some contents. Now I want to open it and add a few more lines to it.

For example, here I open the file

void MainWindow::on_pushButton_readlog_clicked()
{
    QString filename = "logfilename.txt";
    QFile originalFile(filename);

    if(!originalFile.open(QIODevice:: QIODevice::ReadWrite))
    {
        qDebug () << "Error opening Log file: "<<originalFile.errorString();
        return;

    }
    else
    {
        QTextStream instream(& originalFile);
        QString line = instream.readLine();
        while(!instream.atEnd())
        {
            QString line =instream.readLine(); // I can read line by line
            qDebug()<<line;
        }
        originalFile.close();

    }

}

Basically here I want to retain all the contents of the file but add two ​extra texts in the first two lines: Line 1: "Name: ODL12" Line 2: "Device ID: 45R"

Looks like I need to "append" but dont know how to do it in Qt

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0

make a new file and copy content (write) to original file + mods, delete new file or old and rename new.

https://www.cplusplus.com/reference/fstream/ofstream/

https://www.codevscolor.com/c-plus-plus-delete-a-file

https://cplusplus.com/reference/cstdio/rename/

maybe this can be of use for you ... much easier.

#include <fstream>
#include <sstream>
#include <vector>
#include <string>

#include <iostream>

#include <ctime>

using namespace std;

typedef std::vector<string> Vector;

void readReadFile(string &fileName, Vector &array){
    std::ifstream file(fileName);
    if(file.fail()){
            //File does not exist code here
            std::cout << "File doesn't exist." << endl;
            return;
        }
    else{
        std::string str;
        while (std::getline(file, str)) {
            array.push_back(str);
        }
        file.close();
    }

}

void appendstuff(string text, Vector &array){
    array.push_back(text);
}

void writebacktofile(string &fileName, Vector &array){
    // https://stackoverflow.com/questions/17032970/clear-data-inside-text-file-in-c
    std::ofstream myfile;
    myfile.open(fileName, std::ofstream::out | std::ofstream::trunc);
    //myfile.close();

    // write vector back to file
    //ofstream myfile;
    //myfile.open (fileName);
    for(auto& k : array)
        myfile << k << "\n";
    myfile.close();
    array.clear();
}

int main(){
    std::clock_t start;
    double duration;
    start = std::clock();

    Vector temporary;

    string fileName = "input.txt";
    readReadFile(fileName, temporary);

    appendstuff("hello", temporary);
    appendstuff("howdy", temporary);

    writebacktofile(fileName, temporary);

    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
    std::cout<<"printf: "<< duration << " seconds" << '\n';

    return 0;
}

executed in: 0.000295 seconds

NaturalDemon
  • 934
  • 1
  • 9
  • 21