如何在C++中删除文件夹?

use*_*240 39 c++ delete-directory

如何使用C++删除文件夹?

如果不存在跨平台方式,那么如何为最流行的操作系统 - Windows,Linux,Mac,iOS,Android?POSIX解决方案是否适用于所有这些解决方案?

hB0*_*hB0 20

在Windows(VisualC++)中删除不使用Shell API的文件夹(子文件夹和文件),这是最好的工作示例:

#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;
}
Run Code Online (Sandbox Code Playgroud)

资料来源:http://www.codeguru.com/forum/showthread.php? t = 239271

  • 感谢您发布不是Boost或调用system()的内容. (7认同)

Roi*_*ton 18

使用C++ 17 std::filesystem,在C++ 14 std::experimental::filesystem中已经可用.两者都允许使用filesystem::remove().

C++ 17:

#include <filesystem>
std::filesystem::remove("myEmptyDirectoryOrFile"); // Deletes empty directories or single files.
std::filesystem::remove_all("myDirectory"); // Deletes one or more files recursively.
Run Code Online (Sandbox Code Playgroud)

C++ 14:

#include <experimental/filesystem>
std::experimental::filesystem::remove("myDirectory");
Run Code Online (Sandbox Code Playgroud)

注1:这些函数在发生错误时抛出filesystem_error.如果要避免捕获异常,请使用带有std::error_code第二个参数的重载变量.例如

std::error_code errorCode;
if (!std::filesystem::remove("myEmptyDirectoryOrFile", errorCode)) {
    std::cout << errorCode.message() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

注意2:转换是std::filesystem::path从不同的编码隐式发生的,因此您可以将字符串传递给filesystem::remove().


Vin*_*nay 9

该目录应为空.

BOOL RemoveDirectory( LPCTSTR lpPathName );
Run Code Online (Sandbox Code Playgroud)

  • 我认为这只是Windows吗?我发现Vinay有一个Apple头像很有趣,但发布了Windows特定的答案.;) (13认同)

小智 7

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[100] = {0};
                if(*(entry->d_name) != '.')
                {   
                        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);
                                }   
                        }   
                }   
        }   
        remove(path);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

使用SHFileOperation递归删除文件夹


小智 1

C++ 标准定义了remove() 函数,该函数可能会也可能不会删除文件夹,具体取决于实现。如果没有,您需要使用特定于实现的函数,例如 rmdir()。