windows 刪除文件夾下所有文件

windows 刪除文件夾下所有文件

template<typename T>
struct EnsureFileCloseHelper
{
    EnsureFileCloseHelper(T& handle, bool findHandle = false) : t(handle), IsFind(findHandle) {}
    ~EnsureFileCloseHelper() { (!IsFind) ? (::CloseHandle(t)) : (::FindClose(t)); }
    T& t;
    bool IsFind;
};

bool DeleteDirectory(std::wstring & sDirName)
{
    WIN32_FIND_DATA findFileData;
    std::wstring filePathFind = sDirName + _T("\\*.*");
    std::wstring fileName;

    if(sDirName[sDirName.length() - 1] != '\\' && sDirName[sDirName.length() - 1] != '/') { sDirName += L"\\"; } 

    HANDLE hFind = ::FindFirstFile(filePathFind.c_str(), &findFileData);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        EnsureFileCloseHelper<HANDLE> handleHelper(hFind, true);

        while (::FindNextFile(hFind, &findFileData))
        {
            const std::wstring & fileName = findFileData.cFileName;
            if (L"." == fileName || L".." == fileName) 
            {
                continue; 
            }
            else if (FILE_ATTRIBUTE_DIRECTORY == findFileData.dwFileAttributes)
            {
                DeleteDirectory(sDirName + findFileData.cFileName);
            } 
            else if (FILE_ATTRIBUTE_DIRECTORY != findFileData.dwFileAttributes)
            {
                fileName = findFileData.cFileName;
                ::DeleteFile(std::wstring(sDirName + fileName).c_str());
            }
        }
    }

    if(!RemoveDirectory(sDirName.c_str())) 
    { 
        return false; 
    } 

    return true; 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章