This is a directory removal code (rm -r or rmdir equivalent). It deletes all the files or subdirectories under the directory pointed to and also deletes the directory itself:
Signature : bool delTree(QString)
Argument : Path of the directory to be deleted as QString
Return Value: true on success/false on error
bool delTree(QString dir)
{
//Check whether the dir directory exists
if(QDir(dir).exists()){
//Construct an iterator to get the entries in the directory
QDirIterator dirIterator(dir);
while (dirIterator.hasNext()) {
//Get the file information
QString item= dirIterator.next(), fileName= dirIterator.fileName();
QFileInfo fileInfo= dirIterator.fileInfo();
//If entry is a file delete it
if(fileName!="." && fileName!=".."){
if(fileInfo.isFile()){
QFile::remove(item);
}
//If entry is a directory, call the deltree function over it again to traverse it
else if(fileInfo.isDir()){
delTree(item);
}
}
}
}else
return false;
//Move up the directory hierarchy by one level
//Delete the current directory
QDir currentDir(dir);
currentDir.cdUp();
return currentDir.rmdir(dir);
}
No comments:
Post a Comment