使用rmdir函数只能删除空文件夹,对于非空文件夹就无能为力了,这里给出一个实现,用来删除整个文件夹
0、保存当前绝对路径
1、打开要删除的文件夹
2、进入要删除的文件夹
3、读文件夹
4、如果读到的是文件夹,将当前读到的文件夹名称作为参数返回0递归
5、如果不为文件夹调用remove删除
6、返回并调用rmdir删除相应文件夹
下面给代码
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
void error_quit(const char *msg)
{
perror(msg);
exit(-1);
}
void change_path(const char *path)
{
printf("Leave %s Successed . . .\n",getcwd(NULL,0));
if(chdir(path)==-1)
error_quit("chdir");
printf("Entry %s Successed . . .\n",getcwd(NULL,0));
}
void rm_dir(const char *path)
{
DIR *dir;
struct dirent *dirp;
struct stat buf;
char *p=getcwd(NULL,0);
if((dir=opendir(path))==NULL)
error_quit("OpenDir");
change_path(path);
while(dirp=readdir(dir))
{
if((strcmp(dirp->d_name,".")==0) || (strcmp(dirp->d_name,"..")==0))
continue;
if(stat(dirp->d_name,&buf)==-1)
error_quit("stat");
if(S_ISDIR(buf.st_mode))
{
rm_dir(dirp->d_name);
/*if(rmdir(dirp->d_name)==-1)
error_quit("rmdir");
printf("rm %s Successed . . .\n",dirp->d_name);*/
continue;
}
if(remove(dirp->d_name)==-1)
error_quit("remove");
printf("rm %s Successed . . .\n",dirp->d_name);
}
closedir(dir);
change_path(p);
if(rmdir(path)==-1)
error_quit("rmdir");
printf("rm %s Successed . . .\n",path);
}
int main(int argc,char **argv)
return 0;
}
0、保存当前绝对路径
1、打开要删除的文件夹
2、进入要删除的文件夹
3、读文件夹
4、如果读到的是文件夹,将当前读到的文件夹名称作为参数返回0递归
5、如果不为文件夹调用remove删除
6、返回并调用rmdir删除相应文件夹
下面给代码
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
void error_quit(const char *msg)
{
perror(msg);
exit(-1);
}
void change_path(const char *path)
{
printf("Leave %s Successed . . .\n",getcwd(NULL,0));
if(chdir(path)==-1)
error_quit("chdir");
printf("Entry %s Successed . . .\n",getcwd(NULL,0));
}
void rm_dir(const char *path)
{
DIR *dir;
struct dirent *dirp;
struct stat buf;
char *p=getcwd(NULL,0);
if((dir=opendir(path))==NULL)
error_quit("OpenDir");
change_path(path);
while(dirp=readdir(dir))
{
if((strcmp(dirp->d_name,".")==0) || (strcmp(dirp->d_name,"..")==0))
continue;
if(stat(dirp->d_name,&buf)==-1)
error_quit("stat");
if(S_ISDIR(buf.st_mode))
{
rm_dir(dirp->d_name);
/*if(rmdir(dirp->d_name)==-1)
error_quit("rmdir");
printf("rm %s Successed . . .\n",dirp->d_name);*/
continue;
}
if(remove(dirp->d_name)==-1)
error_quit("remove");
printf("rm %s Successed . . .\n",dirp->d_name);
}
closedir(dir);
change_path(p);
if(rmdir(path)==-1)
error_quit("rmdir");
printf("rm %s Successed . . .\n",path);
}
int main(int argc,char **argv)
{
if (argc < 2){
fprintf (stderr, "<用法>: %s + pathname", argv[0]);
return -1;
}
rm_dir(argv[1]);return 0;
}