C语言删除目录

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

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

下面给代码

#include
#include
#include
#include
#include
#include
#include

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)
{
    rm_dir(argv[1]);

    return 0;
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部