简体   繁体   中英

Qt, how do I repetedly read data from file?

I have a file which I would like to read again and again, to update a paramter in my code. but using QTextStream only reads the value once, and reads out 0 after that every time.

This is basically my code:

int main(){
    QString data;
    QFile Status;

    Status.setFileName("/home/user/status");
    Status.open(QIODevice::ReadOnly);

    QTextStream in(&Status);

    While(1){
        usleep(100);
        data = in.readLine();
        cout << "This is the status: " << data.toInt();
    }
return 0;
}

Problem is that it reads the "status" file correctly the fist time, but after that, it reads out "0"...Any thoughts of how I can read out this file again and again.

In additional info, my thought is to change the data of the file to update my app status, which is a number (int) between 0 and 100.

Thank you for any help, it is appreciated.. :)

Close the file and open it again or reset the read pointer.

Since you are going to edit it meanwhile, it is most likely required to close it between reads.

关闭文件并因此释放I / O源怎么样?

Your code doesnt make sense. If you have successfully opened the file, then nobody will be able to open it for writing.

You can modify the loop :

While(1){
    usleep(100);
    if(status.open(QIODevice::ReadOnly) ){
        QbyteArray data = status.readline();//edited
        status.close();
        //read the first line (without newline)
        QString valueString = QString(data).section(0, '\n');
        cout << "This is the status: " << data.toInt();
    }
}

The if is a naive attempt to wait when if the file is opened by another program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM