首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

怎么删除指定目录下的全部文件

2012-01-31 
如何删除指定目录下的全部文件?CArrayCString,CString&delFileLstCStringtmpPath_T( D:\\DEL\\*.* )

如何删除指定目录下的全部文件?
CArray   <   CString,   CString&   >   delFileLst;

      CString   tmpPath   =   _T( "D:\\DEL\\*.* ");
      INT   delCount   =   0;
      INT   fileCount   =   0;

      //先枚举指定目录下的全部文件
        CString   strFileName   =   _T( " ");
        CString   firstName   =   _T( " ");

        WIN32_FIND_DATA   wfd;
        HANDLE   hFind;
        bool   bFind   =   true;

        //查找目录下的全部文件
        hFind   =   FindFirstFile(tmpPath,   &wfd);
        if   (hFind   ==   INVALID_HANDLE_VALUE)
{
FindClose(hFind);      
}
else
{
                              firstName   =   CString(wfd.cFileName);
            if(firstName   !=   ". "   &&   firstName   !=   ".. ")
                                          delFileLst.Add(firstName);
fileCount   =   1;
while(bFind)
{
if(FindNextFile(hFind,   &wfd))
bFind   =   TRUE;
else
bFind   =   FALSE;
if(bFind)
{
                                                        strFileName   =   CString(wfd.cFileName);
if(strFileName   !=   ". "   &&     strFileName   !=   ".. ")
                                                        delFileLst.Add(strFileName);
}
fileCount++;
}
FindClose(hFind);
}

        //以上目录中的全部文件都正确得到了
      for(INT   i   =0;   i   <   delFileLst.GetSize();i++)
      {
        strFileName   =   delFileLst.GetAt(i);
        if(DeleteFile(strFileName))       //此句并没有删除文件(文件没被占用啊)
delCount++;
      }


[解决办法]
strFileName只是文件名,而DeleteFile(strFileName)要成功的话,strFileName必须是文件的完整路径吧
[解决办法]
linchunfu(林雨)说的有道理,你也可以用crumpy() 的方法,这样比较简单点
[解决办法]
void CMainFrame::CDeleteFullFile(CString strDir)
{
CFileFind fh ;
BOOL bfind ;
bfind = fh.FindFile(strDir + "\\*.* ") ;

while (bfind)
{
bfind = fh.FindNextFile() ;
CString strFilePath = fh.GetFilePath() ;
if (fh.IsDots())
{
DeleteFile(strFilePath) ;
}
else if(fh.IsDirectory())
{
CDeleteFullFile(fh.GetFilePath()) ;


RemoveDirectory(fh.GetFilePath()) ;
}
else
{
DeleteFile(strFilePath) ;
}
}
}

[解决办法]
TCHAR szPath[1024];
szOldPath[0]=TEXT( '\0 ');
GetCurrentDirectory(sizeof(szOldPath), szPath);//保存初始状态
SetCurrentDirectory((LPCTSTR)tmpPath); //将指定的搜索目录设为当前目录

for(INT i =0; i < delFileLst.GetSize();i++)
{
...
}

SetCurrentDirectory(szOldPath); //还原初始状态

热点排行