Windows MobileVisual C++ 7.1Visual C++ 8.0Visual C++ 7.0Windows 2003Windows 2000Visual C++ 6.0Windows XPMFC中级开发Visual StudioWindowsC++
删除目录及其子文件夹






2.98/5 (22投票s)
一个删除整个目录结构的功能。
引言
首先,我想说这是我第一次向 CodeProject 贡献,尽管我已经用 C++ 编程五年多了。话虽如此,我认为我有一个很好的理由让我的第一篇文章简短而简单,适合初学者。
删除目录结构
Windows API RemoveDirectory()
函数删除一个现有的空目录。如果目录不为空,该函数将返回零值而失败。但大多数时候,当我们调用一个函数来删除目录时,我们想要的是完全删除目录结构,包括其中的所有文件和子文件夹。
如果你想要这样做,可以使用 DeleteDirectory()
函数来实现。
源代码
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()
函数使用一个小的辅助函数 IsDot()
来检查“.”和“..”目录条目。
BOOL IsDots(const TCHAR* str) { if(_tcscmp(str,".") && _tcscmp(str,"..")) return FALSE; return TRUE; }
解释
DeleteDirectory()
是一个递归函数,它使用 FindFirstFile()
和 FindNextFile()
API 遍历目录结构。如果它找到一个文件,它会删除它。另一方面,如果它找到一个目录条目,它只是递归地调用自身来删除该目录。如果成功,它返回 TRUE
,如果失败,则返回 FALSE
。
这就是它的全部。