Deleting a Directory Along with Sub-Folders

Introduction

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;

TCHAR DirPath[MAX_PATH];
TCHAR FileName[MAX_PATH];

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

// find the first file
hFind = FindFirstFile(DirPath,&FindFileData);
if(hFind == INVALID_HANDLE_VALUE) return FALSE;
_tcscpy(DirPath,FileName);

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

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

Explanation

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