我们知道CfileFind未提供直接遍历其子目录的功能,而有时候我们却常常要遍历某一目录下的所有文 件及其子目录。如我们要删除一个目录,而这个目录下又有子目录,因为Windows不允许删除非空的目录,因此我们必须能够遍历一个目录下的所有子目录, 这可以通过简单的递归实现.

  下面让我们从一个简单的例子开始:如何删除某一目录?(假设我们通过DeleteDirectory(LPCTSTR DirName)函数完成这一功能)

  要删除一个目录,我们要完成下面几步:

  1. 删除该目录下的所有文件

  2. 如果该目录中还有子目录我们要递归地调用DeleteDirectory(LPCTSTR DirName)函数,以删除该子目录下的所有文件

  3. 调用RemoveDirectory(LPCTSTR lpPathName)删除该目录
伪码:
bool deletedir(xx)
{
    while(xx目录里还有文件)
    {
        如果是文件
            删;
        如果是目录
            deletedir(目录);
        找下一个文件;
    }
    删除空目录
}

Code:
// DeleteDirFiles.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <afx.h>//需要设置程序为支持MFC,在Project-Setting, General中选择Using MFC as a Shared Dll类似……………………

BOOL DeleteDirectory(char *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))//此时应该只是一个空目录了
    {
        MessageBox(0,"删除目录失败!","警告信息",MB_OK);
        return FALSE;
    }
    return TRUE;
}

int main(int argc, char* argv[])
{
    DeleteDirectory("C:\\test");
    return 0;
}


posted on 2005-03-12 12:52  dayouluo(.Net学生)  阅读(1617)  评论(0编辑  收藏  举报