/******************
*myrm.c 閫掑綊鐨勫垹闄や竴涓洰褰曘€?
*鏉ㄥ环鍚?2009.4.8
*淇敼锛?
*******************/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<dirent.h>
#include<errno.h>
#include<sys/stat.h>
#include<string.h>
#define SIZE 100
static int R = 0;
static int I = 0;
static int V =0;
/*
* function name : rm
* functon : to remove a dir recursively ,if successful return 0 ,else return -1
* input of function : the path of a dir
* output of functon : integer
*/
void print_result(char *path)
{if(V == 1)
printf("remove: %s/n",path);
}
int sure(char *path)
{
char in='n';
if(I == 1)
{printf("are you sure to remove %s(y/n):",path);
scanf("%c",&in);
while(getchar()!='/n');
if(in == 'y')
return 0;
else
return -1;
}
return 1;
}
int travel(char *path)
{
char next_path[SIZE];
int check = 0;
DIR *dir;
struct dirent *entry;
struct stat buf;
if(lstat(path,&buf) < 0)
{ printf("stat directory or file /"%s/": %s (ERROR %d)/n", path, strerror(errno), errno);
exit(1);
}
if(!S_ISDIR(buf.st_mode))
{ if(unlink(path) < 0)
printf("remove %s : %s ,%d/n",path,strerror(errno),errno);
exit(0);
}
dir = opendir(path);
if (dir == NULL)
{
printf("$$$$Open directory /"%s/": %s (ERROR %d)/n",
path, strerror(errno), errno);
exit(1);
}
while ((entry = readdir(dir)) != NULL)
{
if(strcmp(entry->d_name ,"." ) ==0 || strcmp(entry->d_name ,".." ) ==0 )
continue;
if (entry->d_type == DT_DIR)
{
sprintf(next_path,"%s/%s",path,entry->d_name);
if(R == 1)
{ printf("*********/n");
travel(next_path);
}
}
else
{
sprintf(next_path,"%s/%s",path,entry->d_name);
if(sure(path) >= 0)
{
print_result(next_path);
if(unlink(next_path)<0)
{ printf("remove --%s error/n",entry->d_name);
exit(0);
}
}
else
check = 1;
}
}
closedir(dir);
if(check == 1)
return 0;
if(sure(path) >= 0)
{
if(R == 1)
{ print_result(path);
if(rmdir(path)<0)
{ printf("remove --%s error/n",entry->d_name);
exit(0);
}
}
}
return 0;
}
int main(int argc ,char *argv[1])
{
char *file ;
char path[255];
char name[255];
int len = 0;
int i = 0;
if(argc == 1)
{ printf("more input please!/n");
exit(0);
}
if(argc == 2)
{ V = 0;
I = 0;
R = 0;
strcpy(name,argv[1]);
}
if(argc ==3 )
{ strcpy(name,argv[2]);
len = strlen(argv[1]);
if(argv[1][0]=='-')
for(i=1;i<len;i++)
{ switch(argv[1][i])
{
case 'v': V=1;break;
case 'r': R=1;break;
case 'i' : I=1;break;
default :
printf("no this choice %c/n",argv[1][i]);
exit(1);
break;
}
}
else{ printf("input error/n"); exit(0);}
}
if(argc == 4 )
{
if(strcmp(argv[2],"--") ==0 )
{
strcpy(name,argv[3]);
len = strlen(argv[1]);
if(argv[1][0]=='-')
for(i=1;i<len;i++)
{ switch(argv[1][i])
{
case 'v': V=1;break;
case 'r': R=1;break;
case 'i' : I=1;break;
default :
printf("no this choice %c/n",argv[1][i]);
exit(1);
break;
}
}
else{ printf("input error/n"); exit(0);}
}
else
{ printf("error,input/n");
exit(0);
}
}
file = (char *)getcwd(argv[1],100);
path[0]='/0';
sprintf(path,"%s/%s",file,name);
printf("full path -- %s/n",path);
printf("R=%d V=%d I= %d/n" ,R,V,I);
travel(path);
return 0;
}