VC 遍历指定文件下的所有文件夹和文件 + 删除指定文件夹及下面所有文件及文件夹

来源:互联网 发布:怎样测网络的稳定性 编辑:程序博客网 时间:2024/04/20 20:22
//遍历指定文件下的所有文件夹和文件://摘自 改进《遍历文件夹并建成目录树》;

void BrowseDir( CString strDir/*, HTREEITEM parent*/ )
{
 CFileFind ff;
 CString szDir = strDir;
// HTREEITEM hSubItem;
 
 if(szDir.Right(1) != "\\")
  szDir += "\\";
 
 szDir += "*.*";
 
 BOOL res = ff.FindFile(szDir);

 while( res )
 {
  res = ff.FindNextFile();

  if(ff.IsDirectory()  && !ff.IsDots() ) //文件夹
  {
   CString strPath = ff.GetFilePath();
   CString strTitle = ff.GetFileTitle();
   
 //  hSubItem = m_FileTree.InsertItem( strTitle, 0, 0, parent );
   cout<< strPath.GetBuffer(0) << endl;
   
   BrowseDir( strPath/*, hSubItem*/ );
  }
  else if(!ff.IsDirectory() && !ff.IsDots() ) //文件:
  {
   CString strTitle = ff.GetFileTitle();
   
   // m_FileTree.InsertItem( strTitle, 0, 0, parent );

    cout<< ff.GetFilePath().GetBuffer(0) << endl;
  }
 }
 ff.Close();
}

 

//删除指定文件夹及下面所有文件及文件夹

BOOL DeleteDirectory(char *sDirName)
{
    CFileFind tempFind;
    char sTempFileFind[200] = {0} ;
 
    sprintf(sTempFileFind,"%s\\*.*",sDirName);
    BOOL IsFinded = tempFind.FindFile(sTempFileFind);
    while (IsFinded)
    {
        IsFinded = tempFind.FindNextFile();
  
        if (!tempFind.IsDots())
        {
            char sFoundFileName[200];
            strcpy(sFoundFileName,tempFind.GetFileName().GetBuffer(200));
   
            if (tempFind.IsDirectory())
            {
                char sTempDir[200];
                sprintf(sTempDir,"%s\\%s",sDirName,sFoundFileName);
                DeleteDirectory(sTempDir);
            }
            else
            {
                char sTempFileName[200];
                sprintf(sTempFileName,"%s\\%s",sDirName,sFoundFileName);
                DeleteFile(sTempFileName);
            }
        }
    }
    tempFind.Close();
    if(!RemoveDirectory(sDirName))
    {
        return FALSE;
    }
    return TRUE;
}



原创粉丝点击