Diagnosing QDir::rmdir failure

1.6k views Asked by At

I’m using the following code to delete an empty folder on Linux:

bool removeFolder (const QString& path)
{
   QDir dir(path);
   assert(dir.exists());
   return dir.rmdir(".");
}

For some reason it sometimes returns false (for specific folders, but those folders don’t seem to be wrong in any way). If I subsequently use ::rmdir from <unistd.h> to remove the same folder, it succeeds. How can I tell why QDir::rmdir is failing?

This never happened on Windows so far, QDir::rmdir just works.

3

There are 3 answers

2
Gyll On

Confirming: works on windown, fails on linux.

Reading the "rmdir" doc in <unistd>, here https://pubs.opengroup.org/onlinepubs/007904875/functions/rmdir.html, it says there that "If the path argument refers to a path whose final component is either dot or dot-dot, rmdir() shall fail." So what's probably happening is that QDir::rmdir() is calling the unistd rmdir() function in linux, and this one fails with ".".

I tried to just use the full absolute path ( QDir::rmdir(absolutePath) ) and it worked; however, i see basically no point in using QDir::rmdir() over unistd's rmdir(), so i''ll stick w/ the unistd rmdir() from now on.

note: QDir::removeRecursively() is a different story: it seems to work okay, and it's way more convenient than going through opendir() and then successive readdir()'s (or the nftw(...FTW_DEPTH...) thingie).

0
Guinness On

Try to use this one:

dir.rmdir(dir.absolutePath())
0
HiFile.app - best file manager On

I had the same problem but on Windows, I could not delete an empty directory with QDir().rmdir(path);. This happened on some older hard drive so may be the ancient file system was to blame. But I found a hack:

QFile(path).setPermissions(QFile::WriteOther); // this works even for dirs
bool success = QDir().rmdir(path);

Of course, you should revert the permissions back to original values if the deletion was unsuccessful anyway, but that's a different story.