删除文件夹的几种方法(VC)

本文介绍了在Windows环境下如何删除包含文件和子文件夹的目录。提供了三种不同的C/C++函数实现,包括使用SHFileOperation进行批量删除的方法,并附带了具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

删除文件夹,需要考虑到文件夹内部还有其他文件或文件夹,这样的话windows sdk提供的RemoveDirectory就不能起作用了,需要自己再写一个函数来实现。

RemoveDirectory msdn里面提到了 SHFileOperation,下面就先以SHFileOperation来实现删除文件夹

在vs2010中编译测试过,没有问题,速度也挺快的

//函数名:DeleteFolder
//输入参数:LpszPath 要删除的路径指针
//作用:删除指定文件夹以及里面的文件
//
/////////////////////////////////////
BOOL DeleteFolder(LPCTSTR lpszPath)
{
	int nLength = strlen(lpszPath);
	char *NewPath = new char[nLength+2];
	strcpy(NewPath,lpszPath);
	NewPath[nLength] = '\0';
	NewPath[nLength+1] = '\0';
	SHFILEOPSTRUCT FileOp;
	ZeroMemory((void*)&FileOp,sizeof(SHFILEOPSTRUCT));
	FileOp.fFlags = FOF_NOCONFIRMATION;
	FileOp.hNameMappings = NULL;
	FileOp.hwnd = NULL;
	FileOp.lpszProgressTitle = NULL;
	FileOp.pFrom = NewPath;
	FileOp.pTo = NULL;
	FileOp.wFunc = FO_DELETE;
	return SHFileOperation(&FileOp) == 0;
}

其他两种方式,没有测试过,不过看逻辑好像没有问题:

void   DeleteDirectory(CString   strDir)  
{  
  if(strDir.IsEmpty())  
  return;  
   
  //   首先删除文件及子文件夹  
  CFileFind   ff;  
  BOOL   bFound   =   ff.FindFile(strDir+"\\*",   0);  
  while(bFound)  
  {  
  bFound   =   ff.FindNextFile();  
  if(ff.GetFileName()=="."||ff.GetFileName()=="..")  
  continue;  
  //   去掉文件(夹)只读等属性  
  SetFileAttributes(ff.GetFilePath(),   FILE_ATTRIBUTE_NORMAL);  
  if(ff.IsDirectory())  
  {  
  //   递归删除子文件夹  
  DeleteDirectory(ff.GetFilePath());  
  RemoveDirectory(ff.GetFilePath());  
  }  
  else  
  {  
  //   删除文件  
  DeleteFile(ff.GetFilePath());  
  }  
  }  
  ff.Close();  
   
  //   然后删除该文件夹  
  RemoveDirectory(strDir);  
}


BOOL   DeleteDirectory(LPCTSTR   DirName)  
  {  
  CFileFind     tempFind;    
  char     tempFileFind[200];    
  sprintf(tempFileFind,"%s\\*.*",DirName);    
  BOOL     IsFinded=(BOOL)tempFind.FindFile(tempFileFind);    
  while(IsFinded)    
  {    
  IsFinded=(BOOL)tempFind.FindNextFile();    
  if(!tempFind.IsDots())   //   如果不是'.'或者'..'  
  {    
  char     foundFileName[200];    
  strcpy(foundFileName,tempFind.GetFileName().GetBuffer(200));    
  if(tempFind.IsDirectory())     //是否是目录  
  {    
  char     tempDir[200];    
  sprintf(tempDir,"%s\\%s",DirName,foundFileName);    
  DeleteDirectory(tempDir);    
   
  }    
  else                                           //若是文件,则删除  
  {    
  char     tempFileName[200];    
  sprintf(tempFileName,"%s\\%s",DirName,foundFileName);    
  DeleteFile(tempFileName);    
   
  }    
  }    
  }    
  tempFind.Close();    
  if(!RemoveDirectory(DirName))    
  {    
  AfxMessageBox("删除目录失败!",MB_OK);    
  return     FALSE;    
  }    
  return     TRUE;    
   
  }  

参考文章:

http://www.yuloo.com/news/1007/444817.html

http://xbgd.iteye.com/blog/663025


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值