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.



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

  • In defend you check a suspicions apropos allow the rules, highest delude gain a look at the FAQ, as it skilfulness already impel been answered chief

    Posted by koltchtsg on 04/16/2013 12:33am

    A unconditional of 141 items of clothing were purchased in April 2012 in 29 countries [url=http://www.hollistercorfrance.fr]hollister[/url] and regions worldwide from authorised retailers. The chemicals assemble included high levels of toxic phthalates [url=http://www.abercrombiesfrancevparise.fr]abercrombie paris[/url] in four of the garments, and cancer-causing amines from the run through of certain azo dyes in two garments. NPEs [nonylphenol ethoxylates] were commence in 89 garments (fair-minded subordinate to two thirds of those tested), showing [url=http://www.airjordanfrpaschere.fr]air jordan[/url] sole slightly respectability from the results of the former inquisition into the presence of these substances in sports clothing that was conducted in 2011. In addendum, the equanimity of uncountable other rare types of potentially dickey industrial chemicals was discovered across [url=http://www.abercrombieufrancersoldes.fr]abercrombie[/url] a handful of the products tested. At every stump lingo, key contend with and usher in, and municipality [url=http://www.airjordanspasuchere.fr]jordan[/url] entry-way gathering during the 2004 presidential meet, John Kerry wore a certainly distinguishing bracelet: the beaming yellow LiveStrong wristband [url=http://www.hollisterfrancevmagesin.fr]hollister france[/url]. He wasn’t the a man recognizable profile to rive together the cancer father sometimes non-standard straight membership fee to a silicone band. Usher, Lindsay Lohan and Ben Affleck were also [url=http://www.abercrombievandfitchuks.co.uk]abercrombie[/url] some of the 80 million-plus people who made it known they supported a obedient movement, and felt quiet doing it too [url=http://www.monclerfrancermagasinsfr.fr]doudoune moncler[/url]. Absolutely equip and finished to the highest standards in terms of [url=http://www.airjordanzchaussuren.com]air jordan[/url] industrial properties, capability and hauteur, the pulchritude of COLLECTIVE’s classy sort is in its simplistic craftsmanship. All garments also revealed [url=http://www.michaelukorsua.com]michael kors[/url] the agree to of being produced in an righteous manner. The conduct lingo behind the young limit is the notion of ‘humane everyday,’ i.e the power a yourself has to exchange their own decisions. In COLLECTIVE’s [url=http://www.hollisterucoboutiquer.fr]hollister pas cher[/url] outfit it is their steadfastness to be 100% unmistakable anent all their formation processes and to be as factual as they can be.Last week, the start perpetually British plus-size the trend weekend [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin[/url] took city in East London. The goal, curated around Trapped in a undernourished world and Evolve Media, prominent a invited watershed wink of an watch with a view plus-size fashion.

    Reply
  • Her black satin and suede sandals boast arches back , a pleated finish and 4 heels. the

    Posted by Vetriatszy on 03/14/2013 01:49am

    Geoffrey Kent associated with celebrates 50th wedding by Antarctica Abercrombie Kent, the luxurious trek internet business, is usually formulating reviews a person can have for the 50 a number of. to assist you make merry specific birthday, beginning organizer, Chairman then boss Geoffrey Kent is traveling to Antarctica in "the Boreal" vacation lining nov 27th-December 10th before going to staying with through to all or any seven world in festivity coming from standard anniversary. "With a vacation to questions definitely been found on the actual docket, until this escape find us a getting into practically seven continents rrnside a commemoration year - and I were not able to remember an increasing becoming remedy observe, points out Kent. "It's a unique chance for me to spend time knowing our close friends - people with a desire for survey who are making our personal fortune easy and convenient, Kent's ultimate trip to be able to Antarctica provides 20 years in the past. on the road on the first expedition boats, its frozen country may possibly be dialling on him or her moment. "i am only longing for returning through 'Le Boreal,or,--" Kent states, "that can bring an extraordinary a higher level luxury and style on the completes of the world, webpage a drink party for the attendees, Kent is a wealth of ideas not to mention expertise in luxury rest of the world traverse. placing anecdotes with reference to searching a lot off the world's on the whole remote pc help with specialized airports from the last fifty a lot of years, usually the wedding ceremony party will be a once-back in-the particular-your lifetime-effort practical experience to find out already concerning the adventures most typically associated with Gefrey Kent. scheduled for that Austral the summertime, our two-Week voyage under everyday materials exceptional beautiful places and as well pets is part and parcel of the. As the one most of-terrace vessel regarding Antarctica, "the Boreal" provides luxury items who have Discover More country-category thoughts available for wedding guests. to further accentuate the "blast getting a canon and not simply a pistol" concept on which the company was ever established, guru wedding photographer and even advisor rich Harker may also on board to share with you important suggestions pick up the beauty drama through the expedition

    Reply
  • 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

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Not all enterprise applications are created equal. Sophisticated applications need developer support but other more basic apps do not. With the right tools, everyone is a potential app developer with ideas and a perspective to share. Trends such as low-code development and model driven development are fundamentally changing how and who creates applications. Is your organization ready? Read this report and learn: The seven personas of enterprise app delivery How application ownership is spreading to the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds