C++ Programmer's Cookbook

{C++ 基础} {C++ 高级} {C#界面,C++核心算法} {设计模式} {C#基础}

c++ file and directory 删除,移动,目录浏览对话框,找某目录下的所有文件(包括子目录)

Delete folders, subfolders and files easily

<PRE>void RecursiveDelete(CString szPath)
{
    CFileFind ff;
    CString path 
= szPath;
    
    
if(path.Right(1!= "\\")
        path 
+= "\\";

    path 
+= "*.*";

    BOOL res 
= ff.FindFile(path);

    
while(res)
    
{
        res 
= ff.FindNextFile();
        
if (!ff.IsDots() && !ff.IsDirectory())
            DeleteFile(ff.GetFilePath());
        
else if (ff.IsDirectory())
        
{
            path 
= ff.GetFilePath();
            RecursiveDelete(path);
            RemoveDirectory(path);
        }

    }

}
</PRE>

The CreateDir function creates folders and subfolders thereby completing the whole path passed to it. If the folder already exists, it is left unaffected, but if it doesn't exist, it is created. The CreateDirectory WIN32 API lets us create a directory, but it works only if the parent directory already exists. This function overcomes this limitation.

<PRE>void CreateDir(char* Path)
{
 
char DirName[256];
 
char* p = Path;
 
char* q = DirName; 
 
while(*p)
 
{
   
if (('\\' == *p) || ('/' == *p))
   
{
     
if (':' != *(p-1))
     
{
        CreateDirectory(DirName, NULL);
     }

   }

   
*q++ = *p++;
   
*= '\0';
 }

 CreateDirectory(DirName, NULL);
}
</PRE>

The DeleteAllFiles function deletes all the files (not folders) present in the specified path:

<PRE>void DeleteAllFiles(char* folderPath)
{
 
char fileFound[256];
 WIN32_FIND_DATA info;
 HANDLE hp; 
 sprintf(fileFound, 
"%s\\*.*", folderPath);
 hp 
= FindFirstFile(fileFound, &info);
 
do
    
{
       sprintf(fileFound,
"%s\\%s", folderPath, info.cFileName);
       DeleteFile(fileFound);
 
    }
while(FindNextFile(hp, &info)); 
 FindClose(hp);
}
</PRE>


The EmptyDirectory function deletes all the contents from a specified directory. The RemoveDirectory WIN32 API deletes an existing empty directory, but it doesn't work if the directory isn't empty. This function overcomes this limitation:

<PRE>void EmptyDirectory(char* folderPath)
{
 
char fileFound[256];
 WIN32_FIND_DATA info;
 HANDLE hp; 
 sprintf(fileFound, 
"%s\\*.*", folderPath);
 hp 
= FindFirstFile(fileFound, &info);
 
do
    
{
        
if (!((strcmp(info.cFileName, ".")==0)||
              (strcmp(info.cFileName, 
"..")==0)))
        
{
          
if((info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==
                                     FILE_ATTRIBUTE_DIRECTORY)
          
{
              
string subFolder = folderPath;
              subFolder.append(
"\\");
              subFolder.append(info.cFileName);
              EmptyDirectory((
char*)subFolder.c_str());
              RemoveDirectory(subFolder.c_str());
          }

          
else
          
{
              sprintf(fileFound,
"%s\\%s", folderPath, info.cFileName);
              BOOL retVal 
= DeleteFile(fileFound);
          }

        }

 
    }
while(FindNextFile(hp, &info)); 
 FindClose(hp);
}
</PRE>

浏览目录dialog:
void CTestBrowseDlg::OnBrowse() 
{
    CString str;
    BROWSEINFO bi;
    
char name[MAX_PATH];
    ZeroMemory(
&bi,sizeof(BROWSEINFO));
    bi.hwndOwner
=GetSafeHwnd();
    bi.pszDisplayName
=name;
    bi.lpszTitle
="Select folder";
    bi.ulFlags
=BIF_USENEWUI;
    LPITEMIDLIST idl
=SHBrowseForFolder(&bi);
    
if(idl==NULL)
        
return;
    SHGetPathFromIDList(idl,str.GetBuffer(MAX_PATH));
    str.ReleaseBuffer();
    m_Path
=str;
    
if(str.GetAt(str.GetLength()-1)!='\\')
        m_Path
+="\\";
    UpdateData(FALSE);
}

得到某目录下的所有文件:
void RecursiveDelete(CString szPath)
{
    CFileFind ff;
    CString path 
= szPath;

    
if(path.Right(1!= "\\")
        path 
+= "\\";

    path 
+= "*.*";

    BOOL res 
= ff.FindFile(path);

    
while(res)
    
{
        res 
= ff.FindNextFile();
        
if ( !ff.IsDots()&&ff.IsDirectory())
        
{
            
            path 
= ff.GetFilePath();
            RecursiveDelete(path);
        }

        
else if (!ff.IsDirectory()&&!ff.IsDots())
        
{
            CString ss ; ss
= ff.GetFileName();
            printf(
"%s\n",ss);
            
        }

    }

    ff.Close();
}

posted on 2006-01-12 14:52 梦在天涯 阅读(5750) 评论(4)  编辑 收藏 引用 所属分类: CPlusPlusMFC/QT

评论

# re: c++ file and directory 2006-01-12 15:12 小明

一点小问题:

因为DeleteFile不能Delete掉只读文件,所以最好在DeleteFile之前,使用SetFileAttributes(file,FILE_ATTRIBUTE_NORMAL);  回复  更多评论   

# re: c++ file and directory 2006-01-12 16:39 梦在天涯

也可以用searchpath()来找,是吗?可惜就是没有找到例子!
那位有的话,贡献一下啊,谢谢!  回复  更多评论   

# re: c++ file and directory 2006-02-09 16:49 梦在天涯

-------------------------------------------------------------------
、获得当前应用程序路径
#include < windows.h >
#include < string.h >

HINSTANCE hInst;
char szBuf[256];
char *p;

//拿到全部路径
GetModuleFileName(hInst,szBuf,sizeof(szBuf));

//分离路径和文件名。
p = szBuf;
while(strchr(p,'\\')) {
p = strchr(p,'\\');
p++;
}
*p = '\0';
//路径在szBuf理了。  回复  更多评论   

# re: c++ file and directory 2006-02-20 12:01 blue_bean

用SHFileOperation,可以删除只读文件。


SHFILEOPSTRUCT op;
memset(&op, 0, sizeof(op));
op.pFrom = "c:\\text.ini";
op.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
op.wFunc = FO_DELETE;
if (SHFileOperation(&op) != 0)
{
// delete error
}   回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


公告

EMail:itech001#126.com

导航

统计

  • 随笔 - 461
  • 文章 - 4
  • 评论 - 746
  • 引用 - 0

常用链接

随笔分类

随笔档案

收藏夹

Blogs

c#(csharp)

C++(cpp)

Enlish

Forums(bbs)

My self

Often go

Useful Webs

Xml/Uml/html

搜索

  •  

积分与排名

  • 积分 - 1784859
  • 排名 - 5

最新评论

阅读排行榜