How to delete a folder in C++?

后端 未结 16 1286
悲&欢浪女
悲&欢浪女 2020-12-03 00:45

How can I delete a folder using C++?

If no cross-platform way exists, then how to do it for the most-popular OSes - Windows, Linux, Mac, iOS, Android? Would a POSIX

相关标签:
16条回答
  • 2020-12-03 01:15

    For linux (I have fixed bugs in code above):

    void remove_dir(char *path)
    {
            struct dirent *entry = NULL;
            DIR *dir = NULL;
            dir = opendir(path);
            while(entry = readdir(dir))
            {   
                    DIR *sub_dir = NULL;
                    FILE *file = NULL;
                    char* abs_path new char[256];
                     if ((*(entry->d_name) != '.') || ((strlen(entry->d_name) > 1) && (entry->d_name[1] != '.')))
                    {   
                            sprintf(abs_path, "%s/%s", path, entry->d_name);
                            if(sub_dir = opendir(abs_path))
                            {   
                                    closedir(sub_dir);
                                    remove_dir(abs_path);
                            }   
                            else 
                            {   
                                    if(file = fopen(abs_path, "r"))
                                    {   
                                            fclose(file);
                                            remove(abs_path);
                                    }   
                            }   
                    }
                    delete[] abs_path;   
            }   
            remove(path);
    }
    

    For windows:

    void remove_dir(const wchar_t* folder)
    {
        std::wstring search_path = std::wstring(folder) + _T("/*.*");
        std::wstring s_p = std::wstring(folder) + _T("/");
        WIN32_FIND_DATA fd;
        HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
        if (hFind != INVALID_HANDLE_VALUE) {
            do {
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                    if (wcscmp(fd.cFileName, _T(".")) != 0 && wcscmp(fd.cFileName, _T("..")) != 0)
                    {
                        remove_dir((wchar_t*)(s_p + fd.cFileName).c_str());
                    }
                }
                else {
                    DeleteFile((s_p + fd.cFileName).c_str());
                }
            } while (::FindNextFile(hFind, &fd));
            ::FindClose(hFind);
            _wrmdir(folder);
        }
    }
    
    0 讨论(0)
  • 2020-12-03 01:19

    If you are using windows, then take a look at this link. Otherwise, you may look for your OS specific version api. I don't think C++ comes with a cross-platform way to do it. At the end, it's NOT C++'s work, it's the OS's work.

    0 讨论(0)
  • 2020-12-03 01:20

    Delete folder (sub_folders and files) in Windows (VisualC++) not using Shell APIs, this is the best working sample:

    #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;
    }
    

    Source: http://www.codeguru.com/forum/showthread.php?t=239271

    0 讨论(0)
  • 2020-12-03 01:25

    If you are using the Poco library, here is a portable way to delete a directory.

    #include "Poco/File.h"
    ...
    ...
    Poco::File fooDir("/path/to/your/dir");
    fooDir.remove(true);
    

    The remove function when called with "true" means recursively delete all files and sub directories in a directory.

    0 讨论(0)
  • 2020-12-03 01:26

    You can also try this if you are on linux:

    system("rm -r path");
    
    0 讨论(0)
  • 2020-12-03 01:26

    This works for deleting all the directories and files within a directory.

    #include <iostream>
    #include <cstring>
    #include <cstdlib>
    using namespace std;
    int main()
    {
        cout << "Enter the DirectoryName to Delete : ";
        string directoryName;
        cin >> directoryName;
        string a = "rmdir /s /q " + directoryName;
        system(a.c_str());
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题