#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]);
}
}
240702任伟超8.12作业
最新推荐文章于 2024-08-14 09:28:22 发布