240702任伟超8.12作业

 #include <stdio.h>
 #include <sys/types.h>
 #include <dirent.h>
 #include <unistd.h>
 #include <string.h>
 #include <stdlib.h>
 
 void my_rm(char *argv)    //  1/ 1.txt - 2.txt - 3.txt 2/
                                 //  2/  1.txt 2.txt 3.txt  3/   
                                     //  3/  1.txt 2.txt 3.txt 4/
                                             //4/ 1.txt 2.txt 3.txt
 {
     //1.打开你要删除的目录
     DIR *dp = opendir(argv);
 
         //2.读取该目录
     while(1)
     {
         struct dirent*ep = readdir(dp);//1/   2/  ./1/2
         if(ep == NULL)
         {
             break;
         }
 
         if(strcmp(ep->d_name,".")==0 || strcmp(ep->d_name,"..")==0)
         {
             continue;
         }
 
         //删除目录项其中的普通文件
         if(ep->d_type == DT_REG)
         {
             //strcat(argv[1],ep->d_name);strcat拼接每一次都会把数据拼在argv[1]里面
             //这就导致了argv[1]在最后拼接了很多普通文件的名字,导致路径名错误
             char *pathname = malloc(500);
 
             //用snprintf去拼接字符串
             snprintf(pathname,500,"%s/%s",argv,ep->d_name);
 
             printf("%s\n",pathname);
 
             unlink(pathname);//你要删除的文件路径名,dir-2.txt
                         //  ./dir/2.txt   (argv[1]贴上d_name)
         }
 
         if(ep->d_type == DT_DIR)
         {
             char *pathname = malloc(500);
 
             //用snprintf去拼接字符串
             snprintf(pathname,500,"%s/%s",argv,ep->d_name);//  ./1/2  //./1/2/3  ./1/2/3/4
 
             printf("%s\n",pathname);
 
 
             my_rm(pathname);//  ./1/2  ./1/2/3
 
             rmdir(pathname);//你要删除的文件路径名,dir-2.txt
                         //  ./dir/2.txt   (argv[1]贴上d_name)
         }
 
         rmdir(argv);
     }
 
                                                                                                           
 }
 
 
 int main(int argc,char **argv)
 {
     //删除目录里的所有的目录项(文件和目录)
 
     //my_rm(argv[1]);
     for(int i=1; i<argc; i++)
     {
         my_rm(argv[i]);
     }
 
 
 }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值