Click here to Skip to main content
Licence GPL3
First Posted 16 Dec 2004
Views 87,121
Bookmarked 21 times

Deleting a directory along with sub-folders

By | 16 Dec 2004 | Article
Function that deletes whole of a directory structure.

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;  // 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,"\\");

    hFind = FindFirstFile(DirPath,&FindFileData); // find the first file
    if(hFind == INVALID_HANDLE_VALUE) return FALSE;
    _tcscpy(DirPath,FileName);
        
    bool bSearch = true;
    while(bSearch) { // until we finds 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
                }
                RemoveDirectory(FileName); // remove the empty directory
                _tcscpy(FileName,DirPath);
            }
            else {
                if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
                    _chmod(FileName, _S_IWRITE); // change read-only file mode
                if(!DeleteFile(FileName)) {  // delete the file
                    FindClose(hFind); 
                    return FALSE; 
                }                 
                _tcscpy(FileName,DirPath);
            }
        }
        else {
            if(GetLastError() == ERROR_NO_MORE_FILES) // no more files there
            bSearch = false;
            else {
                // some error occured, close the handle and return FALSE
                FindClose(hFind); 
                return FALSE;
            }

        }

    }
    FindClose(hFind);  // closing file handle
 
    return RemoveDirectory(sPath); // remove the empty directory

}

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.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

Feroz Zahid

Web Developer

Pakistan Pakistan

Member

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.
 



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 4 PinmemberJason Goepel14:05 4 Nov '11  
Generala big 'WOW' PinassociateMohammad Elsheimy11:20 31 Mar '10  
GeneralRe: a big 'WOW' PinmemberFeroz Zahid21:38 31 Mar '10  
GeneralSimple way to delete read only files. Pinmemberanand choubey7:43 24 Feb '09  
GeneralRe: Simple way to delete read only files. PinmemberFeroz Zahid1:31 27 Feb '09  
GeneralDeleteDirectory() misses the first file. PinmemberNeville Franks17:51 3 Dec '07  
GeneralDeleting Empty folders. PinmemberDattaK8:19 23 May '07  
GeneralSimplified code (with bug-fix) Pinmembernaragana12:02 21 Jul '06  
GeneralThanks PinmemberFaxedHead18:49 3 Mar '06  
GeneralDo not use on WinCE Pinmemberhgode22:39 26 Sep '05  
GeneralRe: Do not use on WinCE PinmemberFeroz Zahid2:18 27 Sep '05  
GeneralRe: Do not use on WinCE Pinmemberpaslecode2:55 6 Nov '09  
GeneralRe: Do not use on WinCE PinmemberFeroz Zahid9:15 6 Nov '09  
GeneralRe: Do not use on WinCE PinmemberMember 46770383:27 8 Feb '10  
GeneralRe: Do not use on WinCE PinmemberFeroz Zahid23:28 8 Feb '10  
GeneralA Nice Little Reference... Thanks Pinmemberm. bergman13:01 26 Jan '05  
GeneralRe: A Nice Little Reference... Thanks PinmemberFeroz Zahid3:17 27 Jan '05  
Generalsuggestion PinmemberTodd Smith18:35 18 Dec '04  
GeneralRe: suggestion PinmemberFeroz Zahid3:21 19 Dec '04  
GeneralRead Only Files PinmemberKacee Giger13:40 17 Dec '04  
GeneralRe: Read Only Files PinmemberFeroz Zahid22:27 17 Dec '04  
GeneralRe: Read Only Files PinmemberFeroz Zahid22:39 17 Dec '04  
GeneralWhy reinvent the wheel. PinmemberMr.Prakash3:36 17 Dec '04  
GeneralRe: Why reinvent the wheel. PinmemberThatsAlok19:09 19 Dec '04  
GeneralRe: Why reinvent the wheel. PinmemberMr.Prakash0:33 20 Dec '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 17 Dec 2004
Article Copyright 2004 by Feroz Zahid
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid