Introduction
First of all, let me tell you that this is my first contribution to CodeProject though 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 and simple for beginners.
Deleting a directory structure
The Windows API RemoveDirectory()
function deletes an existing empty directory. If the directory is not empty, function fails with a return value zero. But most of the times, we call a function for removing a directory, what we want is to delete the directory structure completely including all files and sub-folders in it.
If you want this, there's DeleteDirectory()
function to achieve it.
Source Code
BOOL DeleteDirectory(const TCHAR* sPath) {
HANDLE hFind;
WIN32_FIND_DATA FindFileData;
TCHAR DirPath[MAX_PATH];
TCHAR FileName[MAX_PATH];
_tcscpy(DirPath,sPath);
_tcscat(DirPath,"\\*");
_tcscpy(FileName,sPath);
_tcscat(FileName,"\\");
hFind = FindFirstFile(DirPath,&FindFileData);
if(hFind == INVALID_HANDLE_VALUE) return FALSE;
_tcscpy(DirPath,FileName);
bool bSearch = true;
while(bSearch) {
if(FindNextFile(hFind,&FindFileData)) {
if(IsDots(FindFileData.cFileName)) continue;
_tcscat(FileName,FindFileData.cFileName);
if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
if(!DeleteDirectory(FileName)) {
FindClose(hFind);
return FALSE;
}
RemoveDirectory(FileName);
_tcscpy(FileName,DirPath);
}
else {
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
_chmod(FileName, _S_IWRITE);
if(!DeleteFile(FileName)) {
FindClose(hFind);
return FALSE;
}
_tcscpy(FileName,DirPath);
}
}
else {
if(GetLastError() == ERROR_NO_MORE_FILES)
bSearch = false;
else {
FindClose(hFind);
return FALSE;
}
}
}
FindClose(hFind);
return RemoveDirectory(sPath);
}
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 which navigates through a directory structure using 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.
Feroz Zahid has been programming in C/C++ for more than five years now. His experience includes Visual Basic, MFC, ATL, Managed C++ and Client/Server development. He has a strong taste of server side programming using PHP.
He is based in Karachi, Pakistan and works as a freelance programmer.
Feroz Zahid can be reached at ferozzahid [_at_] usa [_dot_] com.