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

本文介绍了一个简单的C语言程序,用于递归地删除指定的文件或目录。该程序利用了POSIX标准中的多个函数,如lstat(), opendir(), readdir() 和 remove()等来实现其功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值