C语言实现递归删除文件夹

使用rmdir函数只能删除空文件夹,对于非空文件夹就无能为力了,这里给出一个实现,用来删除整个文件夹


0、保存当前绝对路径
1、打开要删除的文件夹
2、进入要删除的文件夹
3、读文件夹
4、如果读到的是文件夹,将当前读到的文件夹名称作为参数返回0递归
5、如果不为文件夹调用remove删除
6、返回并调用rmdir删除相应文件夹


下面给代码


#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>


void error_quit(const char *msg)
{
    perror(msg);
    exit(-1);
}


void change_path(const char *path)
{
    printf("Leave %s Successed . . .\n",getcwd(NULL,0));


    if(chdir(path)==-1)
        error_quit("chdir");


    printf("Entry %s Successed . . .\n",getcwd(NULL,0));
}


void rm_dir(const char *path)
{
    DIR *dir;
    struct dirent *dirp;
    struct stat buf;
    char *p=getcwd(NULL,0);


    if((dir=opendir(path))==NULL)
        error_quit("OpenDir");


    change_path(path);


    while(dirp=readdir(dir))
    {
        if((strcmp(dirp->d_name,".")==0) || (strcmp(dirp->d_name,"..")==0))
            continue;


        if(stat(dirp->d_name,&buf)==-1)
            error_quit("stat");


        if(S_ISDIR(buf.st_mode))
        {
            rm_dir(dirp->d_name);
            /*if(rmdir(dirp->d_name)==-1)
                error_quit("rmdir");
            printf("rm %s Successed . . .\n",dirp->d_name);*/
            continue;
        }


        if(remove(dirp->d_name)==-1)
            error_quit("remove");


        printf("rm %s Successed . . .\n",dirp->d_name);
    }


    closedir(dir);
    change_path(p);


    if(rmdir(path)==-1)
        error_quit("rmdir");


    printf("rm %s Successed . . .\n",path);
}


int main(int argc,char **argv)

{

    if (argc < 2){

     fprintf (stderr, "<用法>: %s + pathname", argv[0]);

        return  -1;

     }

    rm_dir(argv[1]);


    return 0;
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值