VC中删除文件夹中内容
方法一:(MFC)
BOOL DeleteDirectory(const CString& csDirPath){ BOOL bRes = FALSE; CString csAllFiles = csDirPath; csAllFiles.Trim(); if(csAllFiles.IsEmpty()) { return FALSE; } CString csRight = csAllFiles.Right(1); if (_T("\") != csRight && _T("/") != csRight) { csAllFiles += _T("\"); } csAllFiles += _T("*.*"); CString csFileFullPath; // First, delete files and its sub directories CFileFind fileFind; // Need include <afx.h> BOOL bFound = fileFind.FindFile(csAllFiles); while(bFound) { bFound = fileFind.FindNextFile(); csFileFullPath = fileFind.GetFilePath(); if (!fileFind.IsDots()) { SetFileAttributes(csFileFullPath, FILE_ATTRIBUTE_NORMAL); // Take off read-only attribute if(fileFind.IsDirectory()) { // recurse to delete directory bRes = DeleteDirectory(csFileFullPath); } else { // delete file bRes = DeleteFile(csFileFullPath); } } } fileFind.Close(); //Delete directory bRes = RemoveDirectory(csDirPath); return bRes;}
?
?
方法二:(WinAPI)
BOOL ExecuteDelete(const CString& csPath, const WIN32_FIND_DATA& find);BOOL DeleteDirectory(const CString& csDirPath){ BOOL bRes = FALSE; CString csPath = csDirPath; csPath.Trim(); if(csPath.IsEmpty()) { return FALSE; } CString csRight = csPath.Right(1); if (_T("\") != csRight && _T("/") != csRight) { csPath += _T("\"); } HANDLE hFind; WIN32_FIND_DATA find; hFind = ::FindFirstFile(csPath + _T("*.*"), &find); if (INVALID_HANDLE_VALUE != hFind) { bRes = ExecuteDelete(csPath, find); while(::FindNextFile(hFind, &find)) { bRes = ExecuteDelete(csPath, find); } ::FindClose (hFind); } bRes = RemoveDirectory(csPath); return bRes;}BOOL ExecuteDelete(const CString& csPath, const WIN32_FIND_DATA& find){ BOOL bRet = FALSE; CString fileName = find.cFileName; if (0 != fileName.Compare(_T(".")) && 0 != fileName.Compare(_T("..")) ) { fileName = csPath + fileName; if (find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { bRet = DeleteDirectory(fileName); } else { bRet = DeleteFile(fileName); } } return bRet;}
??