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;

   TCHAR FileName[MAX_PATH];

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

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

   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.

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.


  • 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=]hollister[/url] and regions worldwide from authorised retailers. The chemicals assemble included high levels of toxic phthalates [url=]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=]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=]abercrombie[/url] a handful of the products tested. At every stump lingo, key contend with and usher in, and municipality [url=]jordan[/url] entry-way gathering during the 2004 presidential meet, John Kerry wore a certainly distinguishing bracelet: the beaming yellow LiveStrong wristband [url=]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=]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=]doudoune moncler[/url]. Absolutely equip and finished to the highest standards in terms of [url=]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=]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=]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=]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.

  • 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

  • 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

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

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

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