Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1588436
  • 博文数量: 441
  • 博客积分: 20087
  • 博客等级: 上将
  • 技术积分: 3562
  • 用 户 组: 普通用户
  • 注册时间: 2006-06-19 15:35
文章分类

全部博文(441)

文章存档

2014年(1)

2012年(1)

2011年(8)

2010年(16)

2009年(15)

2008年(152)

2007年(178)

2006年(70)

分类: C/C++

2008-07-28 11:47:13

在windows编程中, 你有时候可能需要删除一个目录, 然而windows api提供的函数只能删除一个空的目录, 不能删除非空目录, 为了能够删除一个非空目录, 你必须先删除它下面的文件或目录, 这样, 就需要用递归的方法来解决这个问题, 下面是C++代码, 在 windows xp sp2 + vc++6.0下测试通过:


void DeleteDir(CString strDelDir)
{
    CFileFind ff;
    CString strDir, strFile;

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

    strDir += "*.*";

    BOOL bFind = ff.FindFile(strDir);
    while ( bFind )
    {
        bFind = ff.FindNextFile();
        if ( ff.IsDots() )
            continue;
        CString strFileName = ff.GetFileName();

        strFile = strDelDir;
        if ( strFile.Right(1) != "\\" )
            strFile += "\\";
            strFile += strFileName;
        if ( ff.IsDirectory() )
            DeleteDir(strFile);
        else
        {
            if ( ff.IsReadOnly() )
                SetFileAttributes(strFile, GetFileAttributes(strFile) &

                                       (~FILE_ATTRIBUTE_READONLY) );
            DeleteFile(strFile);
            
        }
    }
    ff.Close();
    RemoveDirectory(strDelDir);
    
}


用法:
如: DeleteDir("C:\\Program Files");
或   DeleteDir("C:\\Program Files\\");
不过需要提醒的是, 上面的代码千万别随便的在你的机器上试, 否则, 你的许多程序将无法运行了。^_^
阅读(1627) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~