* Qt Remove Directory and Its Contents
Posted on June 8th, 2010 by John. Filed under programming.
When dealing with directories, Qt has a large number of functions to make manipulating them easy. However, it does not include a way to delete a non-empty directory. This little omission is easily solved.
Following is a recursive function that will delete a directory along with all of it’s contents. This will delete depth first. Meaning it will recurse into sub-directories and only start deleting once the directory has no sub-directories. Changing QDir::DirsFirst to QDir::DirsLast will change this into a breadth first search.
fileutils.h
#ifndef FILEUTILS_H #define FILEUTILS_H #include <QString> class FileUtils { public: static bool removeDir(const QString &dirName); }; #endif // FILEUTILS_H
fileutils.cpp
#include <QDir> #include <QFile> #include <QFileInfo> #include <QFileInfoList> #include "fileutils.h" /*! Delete a directory along with all of its contents. \param dirName Path of directory to remove. \return true on success; false on error. */ bool FileUtils::removeDir(const QString &dirName) { bool result = true; QDir dir(dirName); if (dir.exists(dirName)) { Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) { if (info.isDir()) { result = removeDir(info.absoluteFilePath()); } else { result = QFile::remove(info.absoluteFilePath()); } if (!result) { return result; } } result = dir.rmdir(dirName); } return result; }
Leave a Reply
Tags
backup
bash
batteries
bookeen
c++
calibre
cats
cover
cybook
device interfaces
ebook
electronics
epub
eReader
ezreader pocket pro
fb2
gadgets
GeR2
google
GUI
image
json
KDocker
kindle
Linux
markdown
mobi
N770
nook
palmdoc
pdb
pdf
pgm
pml
pmlz
pyqt
python
qt
rb
release
thumbnail
txt
x11
xlib
ztxt
Archives
- August 2010 (3)
- July 2010 (4)
- June 2010 (1)
- May 2010 (2)
- March 2010 (1)
- January 2010 (8)
- December 2009 (5)
- November 2009 (6)
- October 2009 (4)
- September 2009 (2)
- August 2009 (6)
- July 2009 (6)
- June 2009 (4)
- May 2009 (6)
- April 2009 (4)
- March 2009 (2)
- February 2009 (4)
- January 2009 (4)
- December 2008 (7)
- November 2008 (2)