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

How to rewrite a specific line in a existing file?



  • Hi,
    Brief: I am working on a project in which, after the sensor is calibrated, all its calibrated values are written on to a file as show in the code below:

    //String
     QString calibData = "";
    
     //If channel is == 0
     if(chan_no==0)                       
       {
     //open configch0 file in Write mode
        QFile file("/home/debian/chanconfig/configch0.txt");
        file.open(QIODevice::WriteOnly | QIODevice::Text); 
        QTextStream out(&file);
    
    //Write calibtare value to file and go to next line
        calibData.append(QString("%1").arg((unsigned long)calibtare));    // Write
        calibData.append("\n");
        out << calibData;
    
    //Write fulloadcal value to file and go to next line
        calibData = "";
        calibData.append(QString("%1").arg((unsigned long)fulloadcal));
        calibData.append("\n");
        out << calibData;
    
    //Write calibfactor value to file and go to next line
        calibData = "";
        calibData.append(QString("%1").arg((unsigned long)calibfactor));
        calibData.append("\n");
        out<<calibData;
    
    ////Write fulldp value to file and go to next line
        calibData = "";
        calibData.append(QString("%1").arg((int)fulldp));
        calibData.append("\n");
        out<<calibData;
    
        file.close();
     }
    

    In a particular feature that I am working on, I'd like to re-open this file and replace the 3rd line written by the value "calibfactor" with another value. I know there is a "seek" function in C++, however any examples or snippets on how to use it in QT would be helpful.

    Regards
    ~VD


  • Moderators

    @weedy
    Hello,

    I know there is a "seek" function in C++, however any examples or snippets on how to use it in QT would be helpful.

    Seek makes sense only for binary files (it operates in multiples of a byte), it has no notion of text, characters or lines, you can't use it. Consider what should happen if the text is encoded in an extensible format with changing character size (in bytes) as UTF-8 is, what do you seek then?
    The only reliable way I know of is simply to copy the file line by line, but just substitute the line you want to change.

    By the way, you possibly could use QSettings to store that data instead of maintaining your own text format.


Log in to reply