【轉】VC MFC 如何刪除文件,目錄,文件夾

原文網址:http://shijuanfeng.blogbus.com/logs/100675115.htmlhtml

第一種方法:定義一個文件類對象來操做
CFile   TempFile;   
  TempFile.Remove(指定文件名); 
第二種方法:  使用系統函數 DeleteFile( LPCSTR filename )刪除文件    _rmdir(),刪除目錄 DeleteDirectory(sTempDir);  刪除目錄 RemoveDirectory(sTempDir);刪除目錄
eg:  DeleteFile(   char   *tempFileName);   函數

令注:若要清空文件,但保留目錄用: system(「del  C:\temp」); // 清空了C:\temp中的全部文件,可是不會清楚文件夾下的子目錄,並且會彈出:是否刪除的Doc框 htm

//刪除文件夾目錄(非空) 上面提到的刪除目錄的方法只能刪除空目錄(即文件夾),若是目錄下有文件或者子目錄,就不能刪除了,VC裏好像沒有直接的函數,只能手動寫個函數來刪除了,下面提供一個刪除非空目錄的方法: 對象

bool DeleteDirectory(char* sDirName)
{blog

CFileFind tempFind;
  char sTempFileFind[200];
  strcpy(sTempFileFind, sDirName);
  strcat(sTempFileFind, 「\\*.*」);
 
  BOOL IsFinded = tempFind.FindFile(sTempFileFind);
  while (IsFinded)
  {
   IsFinded = tempFind.FindNextFile();  
  
   char sFoundFileName[200];
   strcpy(sFoundFileName,tempFind.GetFilePath()); 
   DeleteFile(sFoundFileName);   
 }
  tempFind.Close();file

}方法

清空整個文件夾的內容(包括子文件夾),但保留該文件夾刪除文件

void CRelCtrlDlg::DeleteDirectory(char* sDirName)
{
 char sPath[200];
 strcpy(sPath, sDirName);di

 CFileFind   ff;
 BOOL   bFound;
 char sTempFileFind[200];
 strcpy(sTempFileFind, sPath);
 strcat(sTempFileFind, 「\\*.*」);文件

 bFound   =   ff.FindFile(sTempFileFind);

 while(bFound)
 {
  bFound   =   ff.FindNextFile();
  CString  sFilePath   =   ff.GetFilePath();

  if(ff.IsDirectory())  {   if(!ff.IsDots())    DeleteDirectory((LPSTR)(LPCTSTR)sFilePath);  }  else  {   if(ff.IsReadOnly())   {    SetFileAttributes(sFilePath,   FILE_ATTRIBUTE_NORMAL);   }   DeleteFile(sFilePath);  } } ff.Close(); SetFileAttributes(sPath,   FILE_ATTRIBUTE_NORMAL); if (!strcmp(sPath,sDirName)) {  return; } RemoveDirectory(sPath);}

相關文章
相關標籤/搜索