VC MFC刪除指定文件或文件夾內容

1.刪除指定文件

第一種方法:定義一個文件類對象來操作

    CFile    TempFile;   

    TempFile.Remove(指定文件名);


第二種方法:

DeleteFile("c:\\abc\\test.exe ");//MFC框架中可直接調用此函數

2.刪除目錄

_rmdir()

DeleteDirectory(sTempDir)

RemoveDirectory(sTempDir) 

 

//刪除文件夾目錄(非空)

方法一 

bool DeleteDirectory( CString DirName)

{

AfxMessageBox("執行刪除文件夾:"+DirName);

CString PUBPATH;

PUBPATH=DirName;

CFileFind tempFind;

DirName+="\\*.*";

BOOL IsFinded=(BOOL)tempFind.FindFile(DirName);

while(IsFinded)

{

IsFinded=(BOOL)tempFind.FindNextFile();

if(!tempFind.IsDots())

{

CString strDirName;

strDirName+=PUBPATH;

strDirName+="\\";

strDirName+=tempFind.GetFileName();

AfxMessageBox("strDirName :"+strDirName);

if(tempFind.IsDirectory())

{

//strDirName += PUBPATH;

DeleteDirectory(strDirName);

}

else

{

SetFileAttributes(strDirName,FILE_ATTRIBUTE_NORMAL); //去掉文件的系統和隱藏屬性

DeleteFile(strDirName);

}

}

}

tempFind.Close();

if(!RemoveDirectory(PUBPATH))

{

return false ;

}

AfxMessageBox("文件夾刪除成功...");

return true;

}

方法二


bool DeleteDirectory( char* DirName)
{
HANDLE hFirstFile = NULL; 
WIN32_FIND_DATA FindData; 

char currdir[MAX_PATH] = {0};
sprintf(currdir, "%s\\*.*", DirName);

hFirstFile = ::FindFirstFile(currdir, &FindData); 
if( hFirstFile == INVALID_HANDLE_VALUE ) 
   return false;

BOOL bRes = true;

while(bRes) 

   bRes = ::FindNextFile(hFirstFile, &FindData);

   if( (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) //發現目錄
   {
    if( !strcmp(FindData.cFileName, ".") || !strcmp(FindData.cFileName, "..") ) //.或..
     continue;
    else
    {
     char tmppath[MAX_PATH] = {0};
     sprintf(tmppath, "%s\\%s", DirName, FindData.cFileName);
    
     DeleteDirectory(tmppath);
    }
   }
   else               //發現文件
   {
    char tmppath[MAX_PATH] = {0};
    sprintf(tmppath, "%s\\%s", DirName, FindData.cFileName);
    ::DeleteFile(tmppath);    
   }

::FindClose(hFirstFile);
if(!RemoveDirectory(DirName))
{
   return false ;
}
return true;
}

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