Deleting a Directory Along with Sub-Folders

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

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.



About the Author

Feroz Zahid

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.

Comments

  • Question

    Posted by Elie on 08/06/2012 06:14am

    I've got a question, On line 32, you called RemoveDirectory(FileName) which was already called on line 62. I don't understand why

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date