C++ 删除文件夹

来源:互联网 发布:mysql utf8 utf8mb4 编辑:程序博客网 时间:2024/06/18 09:58

这个方法好像是参考Stack Overflow上面的,具体的那篇文章我也忘了!若有看到的可提供下链接,谢谢!

不多说,直接上代码

int DeleteDirectory(const string &refcstrRootDirectory,bool  bDeleteSubdirectories){bool            bSubdirectory = false;       // Flag, indicating whether// subdirectories have been foundHANDLE          hFile;                       // Handle to directorystd::string     strFilePath;                 // Filepathstd::string     strPattern;                  // PatternWIN32_FIND_DATA FileInformation;             // File informationstrPattern = 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 subdirectoryint iRC = DeleteDirectory(strFilePath, bDeleteSubdirectories);if (iRC)return iRC;}elsebSubdirectory = true;}else{// Set file attributesif (::SetFileAttributes(strFilePath.c_str(),FILE_ATTRIBUTE_NORMAL) == FALSE)return ::GetLastError();// Delete fileif (::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 attributesif (::SetFileAttributes(refcstrRootDirectory.c_str(),FILE_ATTRIBUTE_NORMAL) == FALSE)return ::GetLastError();// Delete directoryif (::RemoveDirectory(refcstrRootDirectory.c_str()) == FALSE)return ::GetLastError();}}}return 0;}


原创粉丝点击