windows api實作了這個功能,代碼如下:
[cpp] view plain copy
- BOOL IsDirectory(const char *pDir)
- {
- char szCurPath[500];
- ZeroMemory(szCurPath, 500);
- sprintf_s(szCurPath, 500, "%s/
- if( hFile == INVALID_HANDLE_VALUE )
- {
- FindClose(hFile);
- return FALSE;
- }else
- {
- FindClose(hFile);
- return TRUE;
- }
- }
- BOOL DeleteDirectory(const char * DirName)
- {
- // CFileFind tempFind; //聲明一個CFileFind類變量,以用來搜尋
- char szCurPath[MAX_PATH]; //用于定義搜尋格式
- _snprintf(szCurPath, MAX_PATH, "%s//*.*", DirName); //比對格式為*.*,即該目錄下的所有檔案
- WIN32_FIND_DATAA FindFileData;
- ZeroMemory(&FindFileData, sizeof(WIN32_FIND_DATAA));
- HANDLE hFile = FindFirstFileA(szCurPath, &FindFileData);
- BOOL IsFinded = TRUE;
- while(IsFinded)
- {
- IsFinded = FindNextFileA(hFile, &FindFileData); //遞歸搜尋其他的檔案
- if( strcmp(FindFileData.cFileName, ".") && strcmp(FindFileData.cFileName, "..") ) //如果不是"." ".."目錄
- {
- string strFileName = "";
- strFileName = strFileName + DirName + "//" + FindFileData.cFileName;
- string strTemp;
- strTemp = strFileName;
- if( IsDirectory(strFileName.c_str()) ) //如果是目錄,則遞歸地調用
- {
- printf("目錄為:%s/n", strFileName.c_str());
- DeleteDirectory(strTemp.c_str());
- }
- else
- {
- DeleteFileA(strTemp.c_str());
- }
- }
- }
- FindClose(hFile);
- BOOL bRet = RemoveDirectoryA(DirName);
- if( bRet == 0 ) //删除目錄
- {
- printf("删除%s目錄失敗!/n", DirName);
- return FALSE;
- }
- return TRUE;
- }
使用時,直接調用即可,如:DeleteDirectory("C:");删除c盤下的所有的檔案以及檔案夾,當然對于windows不允許删除的檔案,也是不可以删除的,相關聯的上層檔案夾等等都不可删除,因為不能夠删除非空的檔案夾。
原文位址:http://blog.csdn.net/jaff20071234/article/details/6559533