Qt,我如何反复从文件中读取数据?(Qt, how do I repetedly read data from file?)

编程入门 行业动态 更新时间:2024-10-26 22:28:45
Qt,我如何反复从文件中读取数据?(Qt, how do I repetedly read data from file?)

我有一个文件,我想一遍又一遍读取,以更新我的代码中的参数。 但是使用QTextStream只读取一次该值,然后每次读出0。

这基本上是我的代码:

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; }

问题在于它在第一时间正确地读取了“状态”文件,但在此之后,它读出“0”......关于如何一次又一次读出此文件的任何想法。

在其他信息中,我的想法是更改文件的数据以更新我的应用程序状态,这是一个介于0和100之间的数字(int)。

感谢您的任何帮助,这是表示赞赏.. :)

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.. :)

最满意答案

你的代码没有意义。 如果您已成功打开该文件,则无法将其打开进行写入。

您可以修改循环:

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(); } }

如果该文件是由另一个程序打开的话,if是一个天真的尝试。

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.

更多推荐

本文发布于:2023-08-07 03:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1459787.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   数据   Qt   repetedly   file

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!