Reset QFileDevicePrivate::cachedSize on file close

When a QFile object is reused, the atEnd() method may return incorrect
values. The reason for this is that QFileDevicePrivate::cachedSize is
not cleared. Setting cachedSize = 0 in the close() method fixes this issue.

Task-number: QTBUG-57698
Change-Id: I828a2cf844e98d581098f2c781fa47d2cd3275ce
Reviewed-by: Alex Trotsenko <alex1973tr@gmail.com>
Reviewed-by: Oswald Buddenhagen <oswald.buddenhagen@qt.io>
Reviewed-by: Lars Knoll <lars.knoll@qt.io>
This commit is contained in:
Aleksey Lysenko 2017-01-30 22:55:57 +02:00
parent 5923fb966d
commit f53ab9d736
2 changed files with 65 additions and 0 deletions

View File

@ -328,6 +328,9 @@ void QFileDevice::close()
d->lastWasWrite = false;
d->writeBuffer.clear();
// reset cached size
d->cachedSize = 0;
// keep earlier error from flush
if (d->fileEngine->close() && flushed)
unsetError();

View File

@ -243,6 +243,8 @@ private slots:
void invalidFile_data();
void invalidFile();
void reuseQFile();
private:
enum FileType {
OpenQFile,
@ -3436,5 +3438,65 @@ void tst_QFile::autocloseHandle()
}
}
void tst_QFile::reuseQFile()
{
// QTemporaryDir is current dir, no need to remove these files
const QString filename1("filegt16k");
const QString filename2("file16k");
// create test files for reusing QFile object
QFile file;
file.setFileName(filename1);
QVERIFY(file.open(QIODevice::WriteOnly));
QByteArray ba(17408, 'a');
qint64 written = file.write(ba);
QCOMPARE(written, 17408);
file.close();
file.setFileName(filename2);
QVERIFY(file.open(QIODevice::WriteOnly));
ba.resize(16384);
written = file.write(ba);
QCOMPARE(written, 16384);
file.close();
QVERIFY(file.open(QIODevice::ReadOnly));
QCOMPARE(file.size(), 16384);
QCOMPARE(file.pos(), qint64(0));
QVERIFY(file.seek(10));
QCOMPARE(file.pos(), qint64(10));
QVERIFY(file.seek(0));
QCOMPARE(file.pos(), qint64(0));
QCOMPARE(file.readAll(), ba);
file.close();
file.setFileName(filename1);
QVERIFY(file.open(QIODevice::ReadOnly));
// read first file
{
// get file size without touching QFile
QFileInfo fi(filename1);
const qint64 fileSize = fi.size();
file.read(fileSize);
QVERIFY(file.atEnd());
file.close();
}
// try again with the next file with the same QFile object
file.setFileName(filename2);
QVERIFY(file.open(QIODevice::ReadOnly));
// read second file
{
// get file size without touching QFile
QFileInfo fi(filename2);
const qint64 fileSize = fi.size();
file.read(fileSize);
QVERIFY(file.atEnd());
file.close();
}
}
QTEST_MAIN(tst_QFile)
#include "tst_qfile.moc"