博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux系统调用之文件:递归删除非空目录
阅读量:2516 次
发布时间:2019-05-11

本文共 1115 字,大约阅读时间需要 3 分钟。

  1. #include <sys/types.h>  
  2. #include <dirent.h>  
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5. #include <string.h>  
  6. #include <sys/stat.h>  
  7. #include <unistd.h>  
  8. #define BUF_LEN 1024  
  9.   
  10. //int stat(const char *path, struct stat *buf);  
  11. //int fstat(int filedes, struct stat *buf);  
  12. //int lstat(const char *path, struct stat *buf);  
  13.   
  14. //int remove(const char *pathname);  
  15. //struct dirent *readdir(DIR *dir);  
  16. //DIR *opendir(const char *name);  
  17.   
  18. void rm(char * name)  
  19. {  
  20.     DIR *dir;  
  21.     struct dirent *read_dir;  
  22.     struct stat st;  
  23.     char buf[BUF_LEN];  
  24.   
  25.     if(lstat(name, &st) < 0)  
  26.     {  
  27.         fprintf(stderr, "Lstat Error!/n");  
  28.         exit(1);  
  29.     }  
  30.   
  31.     if(S_ISDIR(st.st_mode))  
  32.     {  
  33.         if((dir = opendir(name)) == NULL)  
  34.         {  
  35.             fprintf(stderr, "remove [%s] faild/n", name);  
  36.             exit(1);  
  37.         }  
  38.       
  39.         while((read_dir = readdir(dir)) != NULL)  
  40.         {  
  41.             if(strcmp(read_dir->d_name, ".") == 0 ||  
  42.                 strcmp(read_dir->d_name, "..") == 0)  
  43.                 continue;  
  44.             sprintf(buf, "%s/%s", name, read_dir->d_name);  
  45.             rm(buf);  
  46.         }  
  47.     }  
  48.     printf("rm :%s/n", name);  
  49.     if(remove(name) < 0)  
  50.     {  
  51.         fprintf(stderr, "remove [%s] faild/n", name);  
  52.     }  
  53. }  
  54.   
  55. int main(int argc, char **argv)  
  56. {  
  57.     if(argc < 1)  
  58.     {  
  59.         fprintf(stderr, "Usage <%s><file>/n", argv[0]);  
  60.     }  
  61.     rm(argv[1]);  
  62.   
  63.     return 0;  
  64. }  

转载地址:http://vuhrb.baihongyu.com/

你可能感兴趣的文章
(Object-C)学习笔记(一)--开发环境配置和与c语言的区别
查看>>
hdu 3549 Flow Problem(最大流模板)
查看>>
编译器错误 CS1026
查看>>
centos安装coreseek
查看>>
gitlab应用
查看>>
$Django importlib与dir知识,手写配置文件, 配置查找顺序 drf分页器&drf版本控制
查看>>
对layoutInflater的理解
查看>>
网络流之最大流问题
查看>>
【自己给自己题目做】之一:椭圆可点击区域
查看>>
Uva 1625 - Color Length(DP)
查看>>
练习2-1 Programming in C is fun!
查看>>
isset函数
查看>>
混合app
查看>>
centos下crontab的使用
查看>>
HTMLParser-实战
查看>>
分布式之缓存击穿
查看>>
从头认识Spring-1.7 如何通过属性注入Bean?(1)-如何通过属性向对象注入值?...
查看>>
$Poj1952\ $洛谷$1687\ Buy\ Low,Buy\ Lower$ 线性$DP+$方案计数
查看>>
linux文件夹打包命令
查看>>
运行cmd状态下MySQL导入导出.sql文件
查看>>