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:
    @
    //myfle.txt
    1243346564
    235456432
    2344324
    32423423434
    234234344565
    344356
    545
    3
    65646457
    645645677721
    @
    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?


  • Moderators

    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);
    offs<<"Line-1"<<"\n";
    //............
    offs<<"Line-n"<<"\n";
    }

    file read method

    QFile file("myfle.txt");
    if (!file.open ( QIODevice::ReadOnly))
    qDebug()<<"File Not Found";
    else
    {
    QTextStream stream ( &file );
    QString line;
    do{
    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 .
    //***************

                    if(1==line.toInt())
                    {
                        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());
    file.close();

    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

    Hi,

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


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.