Linux下删除非空文件夹代码

2019-07-12 18:33发布

linux没有直接删除非空文件夹的函数,下面几个函数删除文件夹,如果文件夹非空则不能删除成功。 int unlink(const char *pathname);
int rmdir(const char *pathname); 
int remove(const char *pathname);  最近编写了一个函数,测试效果还可以。 void dfs_remove_dir() {
DIR *cur_dir = opendir(".");
struct dirent *ent = NULL;
struct stat st;
 
if (!cur_dir)
{
perror("opendir:");
return;
}
 
while ((ent = readdir(cur_dir)) != NULL)
{
stat(ent->d_name, &st);
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
 
if (S_ISDIR(st.st_mode))
{
chdir(ent->d_name);
dfs_remove_dir();
chdir("..");
}
remove(ent->d_name);
}
closedir(cur_dir);
}
 
int rmfile(const char *path_raw)
{
char old_path[100];
if (!path_raw)
return 1;
 
getcwd(old_path, 100);
     
if (chdir(path_raw) == -1)
{
LOG(ERROR)<< path_raw <<" is not a dir or access error ";
return 2;
}
 
//    printf("path_raw : %s ", path_raw);
dfs_remove_dir();
chdir(old_path);
 
    /*如果你想删除该目录本身的话,取消注释*/
unlink(old_path); 
return 0;
}