bool FileUtils::rimraf(const QString &d) { bool s = true; QDir dir(d); if (dir.exists()) { QFileInfoList files = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot, QDir::DirsFirst); if (!files.isEmpty()) { for (QFileInfo fi : files) { if (fi.isDir()) { s = rimraf(fi.absoluteFilePath()); } else { s = QFile::remove(fi.absoluteFilePath()); } if (!s) { return false; } } } s = dir.rmdir(d); } return s; }
int rimraf(const char *path) { DIR *dir = opendir(path); if (NULL == dir) return -1; struct dirent *dp = NULL; while (NULL != (dp = readdir(dir))) { if (0 == strcmp(".", dp->d_name) || 0 == strcmp("..", dp->d_name)) continue; char *f = path_join(path, dp->d_name); if (NULL == f) return -1; struct stat s; if (0 != stat(f, &s)) return -1; if (s.st_mode & S_IFDIR) { // rimraf dirs if (-1 == rimraf(f)) return -1; } else { // unlink files if (-1 == unlink(f)) return -1; } free(f); } free(dp); closedir(dir); return rmdir(path); }
int main(void) { test_setup(); assert(0 == rimraf("./tmp")); assert(false == exists("./tmp/foo/bar/baz/hello")); assert(false == exists("./tmp/foo/bar/hello")); assert(false == exists("./tmp/foo/hello")); assert(false == exists("./tmp/hello")); assert(false == exists("./tmp")); return 0; }