linux系统调用之文件:递归删除非空目录

本文介绍了一个使用C++实现的高效程序,用于清理指定目录下的文件和子目录,确保只保留非隐藏文件及目录,适用于各种操作系统。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值