Qt Remove Directory

Qt Remove Directory

Qt have rich QDir class provides access to directory structures and their contents. QDir have function QDir::rmdir to remove directory. The directory must be empty for rmdir() to succeed. This Qt Remove Directory function Returns true if successful,  otherwise returns false. The problem is how Qt Remove Directory if that directory not empty? If you have non empty directory, you can use this Qt Remove Directory function to remove non empty directory with all subdirectory. This is a Qt Remove Directory function :

bool frameWorkspace::removeDirectory( 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;
}

You can call this Qt Remove Directory function with this method :

QDir dir;
dir.setPath("/your/sample/directory");
removeDirectory(dir);

If you have any question or method about this Qt Remove Directory, please share to us.

 
Source :
http://www.archivum.info/qt-interest@trolltech.com/2009-09/00049/Re-%28Qt-interest%29-What-should-I-use-to-delete-non-empty-directories.html
5 Comments

Add a Comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.