zoukankan      html  css  js  c++  java
  • C语言实现Linux下删除非空目录

    #include <sys/stat.h>
    #include <dirent.h>
    #include <fcntl.h>
    
    /**
    * 递归删除目录(删除该目录以及该目录包含的文件和目录)
    * @dir:要删除的目录绝对路径
    */
    int remove_dir(const char *dir)
    {
        char cur_dir[] = ".";
        char up_dir[] = "..";
        char dir_name[128];
        DIR *dirp;
        struct dirent *dp;
        struct stat dir_stat;
    
        // 参数传递进来的目录不存在,直接返回
        if ( 0 != access(dir, F_OK) ) {
            return 0;
        }
    
        // 获取目录属性失败,返回错误
        if ( 0 > stat(dir, &dir_stat) ) {
            perror("get directory stat error");
            return -1;
        }
    
        if ( S_ISREG(dir_stat.st_mode) ) {  // 普通文件直接删除
            remove(dir);
        } else if ( S_ISDIR(dir_stat.st_mode) ) {   // 目录文件,递归删除目录中内容
            dirp = opendir(dir);
            while ( (dp=readdir(dirp)) != NULL ) {
                // 忽略 . 和 ..
                if ( (0 == strcmp(cur_dir, dp->d_name)) || (0 == strcmp(up_dir, dp->d_name)) ) {
                    continue;
                }
    
                sprintf(dir_name, "%s/%s", dir, dp->d_name);
                remove_dir(dir_name);   // 递归调用
            }
            closedir(dirp);
    
            rmdir(dir);     // 删除空目录
        } else {
            perror("unknow file type!");    
        }
    
        return 0;
    }
    
    
    int main()
    {
        string dstpath = "/DATA/123";
    
        //如果目录存在就删除目录
        if (access(dstpath.c_str(), 0) == 0)  
        {
            cout << "remove " << dstpath << endl;
            int flag = remove_dir(dstpath.c_str()); 
            cout << flag << endl; 
        }
    }
  • 相关阅读:
    jQuery技巧大放送
    网页挂马工作原理完全分析
    C#常见问题
    网站优化之页面优化
    SQL大全分享
    获得本机的可用的所有打印机
    C#文件操作方法大全
    编程范式及其代表语言
    23种模式简說
    C# Open Source
  • 原文地址:https://www.cnblogs.com/adong7639/p/9070753.html
Copyright © 2011-2022 走看看