[Qt-interest] What should I use to delete non-empty directories?

Brad Howes howes at ll.mit.edu
Mon Sep 14 15:27:12 CEST 2009


On Sep 14, 2009, at 3:31 AM, Radosław Papierski wrote:

> I'm trying to delete a non-empty directory. Which model/class should  
> I use? I tried QDirModel, but it returns false when trying to rmdir.
>
> As a sidenote, it's really annoying there's no return/error codes in  
> Qt.

Here's a utility function I have in my GUI toolbox/namespace that I  
use to delete a directory. And I like Qt's handling of errors in a  
platform-neutral way.

bool
GUI::RemoveDirectory( const QDir& dir )
{
     bool ok = dir.exists();
     if ( ok ) {
	QFileInfoList entries = dir.entryInfoList( QDir::NoDotAndDotDot |
						   QDir::Dirs | QDir::Files );
	foreach ( QFileInfo entryInfo, entries ) {
	    QString path = entryInfo.absoluteFilePath();
	    if ( entryInfo.isDir() ) {
		if ( ! RemoveDirectory( QDir( path ) ) ) {
		    ok = false;
		    break;
		}
	    }
	    else {
		QFile file( path );
		if ( ! file.remove() ) {
		    ok = false;
		    break;
		}
	    }
	}
     }

     if ( ok && ! dir.rmdir( dir.absolutePath() ) )
	ok = false;

     return ok;
}

-- 
Brad Howes
Group 42
MIT Lincoln Laboratory • 244 Wood St. • Lexington, MA 02173
Phone: 781.981.5292 • Fax: 781.981.3495 • Secretary: 781.981.7420








More information about the Qt-interest-old mailing list