CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Windows SDK File System: How to delete a directory and subdirectories?

    Q: How to delete a directory and subdirectories?

    A:

    Code:
    #include <string>
    #include <iostream>
    
    #include <windows.h>
    #include <conio.h>
    
    
    int DeleteDirectory(const std::string &refcstrRootDirectory,
                        bool              bDeleteSubdirectories = true)
    {
      bool            bSubdirectory = false;       // Flag, indicating whether
                                                   // subdirectories have been found
      HANDLE          hFile;                       // Handle to directory
      std::string     strFilePath;                 // Filepath
      std::string     strPattern;                  // Pattern
      WIN32_FIND_DATA FileInformation;             // File information
    
    
      strPattern = refcstrRootDirectory + "\\*.*";
      hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
      if(hFile != INVALID_HANDLE_VALUE)
      {
        do
        {
          if(FileInformation.cFileName[0] != '.')
          {
            strFilePath.erase();
            strFilePath = refcstrRootDirectory + "\\" + FileInformation.cFileName;
    
            if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
              if(bDeleteSubdirectories)
              {
                // Delete subdirectory
                int iRC = DeleteDirectory(strFilePath, bDeleteSubdirectories);
                if(iRC)
                  return iRC;
              }
              else
                bSubdirectory = true;
            }
            else
            {
              // Set file attributes
              if(::SetFileAttributes(strFilePath.c_str(),
                                     FILE_ATTRIBUTE_NORMAL) == FALSE)
                return ::GetLastError();
    
              // Delete file
              if(::DeleteFile(strFilePath.c_str()) == FALSE)
                return ::GetLastError();
            }
          }
        } while(::FindNextFile(hFile, &FileInformation) == TRUE);
    
        // Close handle
        ::FindClose(hFile);
    
        DWORD dwError = ::GetLastError();
        if(dwError != ERROR_NO_MORE_FILES)
          return dwError;
        else
        {
          if(!bSubdirectory)
          {
            // Set directory attributes
            if(::SetFileAttributes(refcstrRootDirectory.c_str(),
                                   FILE_ATTRIBUTE_NORMAL) == FALSE)
              return ::GetLastError();
    
            // Delete directory
            if(::RemoveDirectory(refcstrRootDirectory.c_str()) == FALSE)
              return ::GetLastError();
          }
        }
      }
    
      return 0;
    }
    
    
    int main()
    {
      int         iRC                  = 0;
      std::string strDirectoryToDelete = "c:\\mydir";
    
    
      // Delete 'c:\mydir' without deleting the subdirectories
      iRC = DeleteDirectory(strDirectoryToDelete, false);
      if(iRC)
      {
        std::cout << "Error " << iRC << std::endl;
        return -1;
      }
    
      // Delete 'c:\mydir' and its subdirectories
      iRC = DeleteDirectory(strDirectoryToDelete);
      if(iRC)
      {
        std::cout << "Error " << iRC << std::endl;
        return -1;
      }
    
      // Wait for keystroke
      _getch();
    
      return 0;
    }
    As Paul McKenzie just pointed out: I am not responsible for any possible damage this function might do to a system (like calling it with 'c:\\')...


    Last edited by Andreas Masur; July 24th, 2005 at 05:19 PM.

  2. #2
    Join Date
    Oct 2002
    Location
    Timisoara, Romania
    Posts
    14,360
    Q: How to delete a directory and its subdirectories using the Shell API?

    A: You can use 'SHFileOperation', which copies, removes, renames or deletes a file system object. In the example below it is used to delete a folder in a recursive manner:

    Code:
    #include <windows.h>
    #include <tchar.h>
    #include <shellapi.h>
    
    bool DeleteDirectory(LPCTSTR lpszDir, bool noRecycleBin = true)
    {
      int len = _tcslen(lpszDir);
      TCHAR *pszFrom = new TCHAR[len+2];
      _tcscpy(pszFrom, lpszDir);
      pszFrom[len] = 0;
      pszFrom[len+1] = 0;
      
      SHFILEOPSTRUCT fileop;
      fileop.hwnd   = NULL;    // no status display
      fileop.wFunc  = FO_DELETE;  // delete operation
      fileop.pFrom  = pszFrom;  // source file name as double null terminated string
      fileop.pTo    = NULL;    // no destination needed
      fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT;  // do not prompt the user
      
      if(!noRecycleBin)
        fileop.fFlags |= FOF_ALLOWUNDO;
    
      fileop.fAnyOperationsAborted = FALSE;
      fileop.lpszProgressTitle     = NULL;
      fileop.hNameMappings         = NULL;
    
      int ret = SHFileOperation(&fileop);
      delete [] pszFrom;  
      return (ret == 0);
    }
    
    int main() 
    {
      DeleteDirectory("d:\\Test", false);
      return 0;
    }
    Last edited by Andreas Masur; July 24th, 2005 at 05:20 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured