Deleting a Directory Along with Sub-Folders


First of all, let me tell you that this is my first contribution to CodeGuru although I have been programming in C++ for more than five years now. Having said that, I think, I have good reasons to keep my first article short, simple, and for beginners.

Deleting a Directory Structure

The Windows API RemoveDirectory() function deletes an existing empty directory. If the directory is not empty, the function fails with a return value of zero. But most of the time, when you call a function for removing a directory, what you want is to delete the directory structure completely—including all files and sub-folders in it.

If you want this ability, here’s the DeleteDirectory() function to acheive it.

Source Code

BOOL DeleteDirectory(const TCHAR* sPath) {
HANDLE hFind; // file handle
WIN32_FIND_DATA FindFileData;


_tcscat(DirPath,”\*”); // searching all files

// find the first file
hFind = FindFirstFile(DirPath,&FindFileData);

bool bSearch = true;
while(bSearch) { // until we find an entry
if(FindNextFile(hFind,&FindFileData)) {
if(IsDots(FindFileData.cFileName)) continue;
if((FindFileData.dwFileAttributes &

// we have found a directory, recurse
if(!DeleteDirectory(FileName)) {
return FALSE; // directory couldn’t be deleted
// remove the empty directory
else {
if(FindFileData.dwFileAttributes &
// change read-only file mode
_chmod(FileName, _S_IWRITE);
if(!DeleteFile(FileName)) { // delete the file
return FALSE;
else {
// no more files there
if(GetLastError() == ERROR_NO_MORE_FILES)
bSearch = false;
else {
// some error occurred; close the handle and return FALSE
return FALSE;


FindClose(hFind); // close the file handle

return RemoveDirectory(sPath); // remove the empty directory


The DeleteDirectory() function uses a small companion IsDot() for checking ‘.’ and ‘..’ directory entries.

BOOL IsDots(const TCHAR* str) {
if(_tcscmp(str,”.”) && _tcscmp(str,”..”)) return FALSE;
return TRUE;


DeleteDirectory() is a recursive function that navigates through a directory structure using the FindFirstFile() and FindNextFile() APIs. If it finds a file, it deletes it. On the other hand, if it finds a directory entry, it just calls itself to recursively delete the directory. It returns TRUE on success and FALSE on failure.

That’s all there’s to it.

More by Author

Must Read