Important: Please read the Qt Code of Conduct -

Read and write a file to a specific line

  • I've to store some long int data into a file (one long int per line).
    Each line, must only contains the long int value and my problem is how can I write (on first) and than read the specific value on this file?
    this is an example file:
    The write procedure must be sequantial (write first line, than the second, than the third...), but with the read procedure, I must readthe long int data on second line, than data on first, than... (is not a sequantially function).
    Can anyone help me?

  • If I understand you correctly you have a plain text file and directly after the end of each number you have the end of line.

    If this is the case the writing is standard and I guess you know already how to do the sequential write.
    The reading is not trivial as long as the file is the only information you have. There is no way to know where the next line is starting. Therefore, you need to read line by line and through the ones you do not want to read every time you have to access a line.

  • hi..

    at write time use this
    void fileSave(QString fname)
    QString fileName = fname;
    std::string file2;
    file2 =fileName.toStdString();
    const char *filename = file2.c_str();
    std::ofstream offs(filename);

    file read method

    QFile file("myfle.txt");
    if (! ( QIODevice::ReadOnly))
    qDebug()<<"File Not Found";
    QTextStream stream ( &file );
    QString line;
    line = stream.readLine();

    int nvalue = convert(); // write a method find line data string //(Line-1 type string ) or long int data.
    //if it is string type devide Line-1 to Line- and 1 and return 1 to nvalue .

                        rtemp=1; // means found required line otherwise init as 0
            else if(rtemp==1 && line.toInt()!=1)
                        qDebug()<<"In Red data"<<line.toDouble();

    rtemp =0;
    } while (!line.isNull());

    hope you understand this method. if u are not understand follow these steps

    1. give an int value in every line for line no at write mode.
      2.check condition what you want reqired line in read mode.

  • Lifetime Qt Champion


    Please enclose your code with coding tags. It's very difficult to read it without

Log in to reply