PDA

View Full Version : How to read changing file contents



tomkonikkara
9th July 2011, 15:09
I've a file named 'file.txt'. Its contents changes with time. How can i read it? I tested it using QFile class. But once read, data is not changing until application restarts.
Then i tried making file object and destructing each time i read the file, but no use. Once the file is read there's no change in the contents. Is there any way?

Talei
9th July 2011, 19:32
I can see few options here:
1. calculate MD5/CRC (any hash) of the file that You read, store that hash and periodically compute new one and compare it with the one that You store, is oldHash != newHash file.readAll() etc.
2. check file attribute: last modified and store it after Your last access (from Your program) and compare it periodically

probably there are more.

d_stranz
9th July 2011, 22:38
Try using QFileSystemWatcher and connect to the fileChanged() signal. When the signal is sent with the name of the file you are interested in, then you know it has changed. At that point, you can re-read the file.

When you read the file with QFile, you basically create a copy in memory of the contents of the file at the time you read it. This in-memory data does not change when the file changes, because it is a copy.

If you want the in-memory data to be up to date, then you need to watch the file for changes (which QFileSystemWatcher will do for you) and re-read the file when you see it has changed. Be sure to close the file after you read it, otherwise the other app that is changing it may not be able to open it if you have it open and locked.

tomkonikkara
10th July 2011, 18:56
The method both of you described to find the change in file may be correct. But actually that isn't my problem.
call readAll()
a change is made in the file externally.
call readAll()
in both calls, i am getting same result. That means, the change is not seen on the output.

d_stranz
10th July 2011, 19:11
Close the file, then reopen it, or create a new QTextStream each time you want to read it. QTextStream caches the file contents on the first readAll(), so when you ask for it again, you get the same thing. You could try calling seek( 0 ), but that still might not empty the cache.