Remove useless readdir() calls in Dir::isEmpty()

simgear::Dir::isEmpty() used to make up to 5 calls to readdir(), while 3
are enough to say whether the directory has entries other than '.' and
'..'.

Also add an automated test for this method.
This commit is contained in:
Florent Rougon
2017-10-27 20:49:17 +02:00
parent 7a374c43dc
commit 880c063d04
2 changed files with 29 additions and 1 deletions

View File

@@ -296,7 +296,10 @@ bool Dir::isEmpty() const
int n = 0;
dirent* d;
while( (d = readdir(dp)) !=NULL && (n < 4) ) n++;
while (n < 3 && (d = readdir(dp)) != nullptr) {
n++;
}
closedir(dp);
return (n == 2); // '.' and '..' always exist

View File

@@ -2,6 +2,7 @@
#include <cstdlib>
#include <simgear/io/iostreams/sgstream.hxx>
#include <simgear/misc/sg_path.hxx>
#include <simgear/misc/test_macros.hxx>
#include "sg_dir.hxx"
@@ -34,11 +35,35 @@ void test_tempDir()
d.remove();
}
void test_isEmpty()
{
simgear::Dir d = simgear::Dir::tempDir("FlightGear");
SG_VERIFY(!d.isNull() && d.exists() && d.isEmpty());
SGPath f = d.file("some file");
{ sg_ofstream file(f); } // create and close the file
SG_VERIFY(!d.isEmpty());
f.remove();
SG_VERIFY(d.isEmpty());
simgear::Dir subDir{d.file("some subdir")};
subDir.create(0777);
SG_VERIFY(!d.isEmpty());
subDir.remove();
SG_VERIFY(d.isEmpty());
d.remove();
SG_VERIFY(d.isEmpty()); // eek, but that's how it is
}
int main(int argc, char **argv)
{
test_isNull();
test_setRemoveOnDestroy();
test_tempDir();
test_isEmpty();
return EXIT_SUCCESS;
}