Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to insert the value into certain n th line and column of my text file.



  • I am using qt creator and newbie. I want to insert the value of double spin box on 14th line and 19th column of my large text file. I have created loop to insert the value on 14th line, but it is just placed on first column of the line. Can anyone help me to move the value after text, parameter PW_x = ?

    This is the portion of my text file.

    parameter PW_x = "i want to insert value here" "this is 14th line and 19th column"
    parameter PW_y =
    parameter PD =
    parameter PC =

    This is my code

    void MainWindow::on_doubleSpinBox_6_editingFinished()
    {
    QString file("D:\my text file name");
    QFile outputFile(file);
    if (outputFile.open(QIODevice::ReadWrite | QIODevice::Text))
    {
    for (int i=0;i<13;i++) {
    outputFile.readLine();
    }
    QTextStream stream(&outputFile);
    stream << QString::number(ui->doubleSpinBox_6->value());
    }


  • Lifetime Qt Champion

    @hajh90 said in How to insert the value into certain n th line and column of my text file.:

    but it is just placed on first column of the line

    The problem is that you can't directly insert in a file. If you write something on some position in a file you overwrite what was there before. You should do it differently: open a temporary file, read from original file all the lines until 14th and write them into the temp file. Then you write the new line into the temp file and read all the other stuff from original file and write it into the temp file. When finished delete original file and rename the temp file, so it get the name of original file.



  • @jsulm said in How to insert the value into certain n th line and column of my text file.:

    . Then you write the new line into the temp file and read all the other stuff from original file and write it into the temp file. When finished delete original file and rename the temp file, so it get the name of original file.

    Thanks. Then can i just write the value with the macro? Make the code that the "parameter PW_x =" is inserted before the double spin value always automatically ? When i type the value of GUI, the value is always come with parameter PW_x= "double spin box value"


  • Lifetime Qt Champion

    @hajh90 Not sure I understand you. If you want to overwrite an existing value and this value always has same amount of characters in the file, then you can search for PW_x= in the file and overwrite the value.
    Like:

    PW_x=ABC
    

    becomes

    PW_x=XYZ
    

    But this only works as long as the value always has same length.
    "Then can i just write the value with the macro?" - what macro do you mean?


Log in to reply