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;
}

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值