递归地删除目录

写程序时用到一个删除目录的功能,但C库函数提供的_rmdir() 只能删除空目录,在网上搜索了一下也没得到满意的答案,于是就自己写了个小程序,递归地删除目录下的内容,最后删除目录本身。

主要用到了以下函数:

_access(); /*判断目录是否存在*/

_chdir(); /*改变当前工作目录*/

_findfirst(); /*在目录下查找第一个文件或文件夹*/

_findnext(); /*在目录下查找下一个文件或文件夹*/

_findclose(); /*结束一个查找操作*/

remove(); /*删除一个文件*/

_rmdir(); /*删除一个空目录*/

 

代码如下(下面的程序将直接删除文件或文件夹,而不是移到回收站,虽然已经多次测试,但为了安全起见,准备调试下面程序的朋友请做好备份,或将删除文件和文件夹的函数替换为输出文件名):

复制代码
#include "io.h"
#include "direct.h"

#include <iostream>
using std::cin;
using std::cerr;
using std::cout;
using std::endl;

#include <string>
using std::string;

void empty_directory(/*const char* dirName*/);

int main()
{
    string path;
    cout << "Input name of the directory you want to remove: ";
    cin >> path;

    if (_access(path.c_str(), 06) == -1)
    {
        cerr << "error: directory does not exist." << endl;
        exit(-1);
    }

    if (path.at(path.length() - 1) != '\\')
    {
        path += '\\';
    }

    _chdir(path.c_str());

    empty_directory();

    _chdir(path.c_str());
    _chdir("..");
    _rmdir(path.c_str());


    return 0;
}


void empty_directory( /*const char* dirName*/ )
{
    _finddata_t fileinfo;
    memset(&fileinfo, 0x0, sizeof(fileinfo));


    intptr_t iFind = _findfirst("*", &fileinfo);
    if (iFind == -1)
    {
        cerr << "error: _findfirst failed." << endl;
        return;
    }

    /* process the first item */
    if (fileinfo.name[0] != '.')
    {
        if ((fileinfo.attrib & _A_SUBDIR) != 0)
        {
            /* process directory */
            _chdir(fileinfo.name);
            empty_directory(/*fileinfo.name*/);
            _chdir("..");
            _rmdir(fileinfo.name);
            
        }
        else
        {
            /* process file */
            remove(fileinfo.name);
        }
    }


    while (_findnext(iFind, &fileinfo) == 0)
    {
        if (fileinfo.name[0] != '.')
        {
            if ((fileinfo.attrib & _A_SUBDIR) != 0)
            {
                /* process directory */
                _chdir(fileinfo.name);
                empty_directory(/*fileinfo.name*/);
                _chdir("..");
                _rmdir(fileinfo.name);
            }
            else
            {
                /* process file */
                remove(fileinfo.name);
            }
        }

    }

    _findclose(iFind);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值