From 03ac8f83498aa906b20726ee14caefbe6b668864 Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Thu, 27 Mar 2025 19:30:01 +0200 Subject: [PATCH] QDirIterator: next() should return empty string after reaching the end Amends c7691842f743f568a073582c8f0cacd6ee188f98, and actually fixes the other half of QTBUG-130142. Fix the unittest, it was wrong to begin with, iterating over an empty string with NoDotAndDotDot, next() will always return an empty string because `currentFileInfo` has never been initialized. Pick-to: 6.8 Fixes: QTBUG-135287 Task-number: QTBUG-130142 Change-Id: I9966428c7a143803e6e934b5970ea6b6afc8a08f Reviewed-by: Thiago Macieira (cherry picked from commit 4fd7d31e0966d52af4dc40c7e47576d40d8b00ab) Reviewed-by: Qt Cherry-pick Bot --- src/corelib/io/qdiriterator.cpp | 4 +++- .../corelib/io/qdiriterator/tst_qdiriterator.cpp | 14 +++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/corelib/io/qdiriterator.cpp b/src/corelib/io/qdiriterator.cpp index f9bf1b2abe1..c10f1ecd69c 100644 --- a/src/corelib/io/qdiriterator.cpp +++ b/src/corelib/io/qdiriterator.cpp @@ -106,8 +106,10 @@ public: // Match the behavior of advance() from before porting to QDirListing, // that is, even if hasNext() returns false, calling next() returns an // empty string without crashing. QTBUG-130142 - if (it == lister.end()) + if (it == lister.end()) { + currentFileInfo = {}; return; + } currentFileInfo = nextFileInfo; if (++it != lister.end()) { nextFileInfo = it->fileInfo(); diff --git a/tests/auto/corelib/io/qdiriterator/tst_qdiriterator.cpp b/tests/auto/corelib/io/qdiriterator/tst_qdiriterator.cpp index dd37c20239c..d4ae8c16118 100644 --- a/tests/auto/corelib/io/qdiriterator/tst_qdiriterator.cpp +++ b/tests/auto/corelib/io/qdiriterator/tst_qdiriterator.cpp @@ -646,10 +646,18 @@ void tst_QDirIterator::hiddenDirs_hiddenFiles() void tst_QDirIterator::hasNextFalseNoCrash() { - QDirIterator iter(u"empty"_s, QDir::NoDotAndDotDot); - // QTBUG-130142 - // No crash if you call next() after hasNext() returned false + QVERIFY(QFileInfo(u"empty"_s).exists()); + QDirIterator iter(u"empty"_s); + int count = 0; + while (iter.hasNext()) { + iter.next(); + ++count; + } + QVERIFY(count > 0); QVERIFY(!iter.hasNext()); + // QTBUG-130142 + // When the iteration reaches the end, calling next() returns an empty string + // and no crash happens QVERIFY(iter.next().isEmpty()); }