Linux下删除非空文件夹代码
2016-04-15 17:03
681 查看
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\n";
return 2;
}
// printf("path_raw : %s\n", path_raw);
dfs_remove_dir();
chdir(old_path);
/*如果你想删除该目录本身的话,取消注释*/
unlink(old_path);
return 0;
}
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\n";
return 2;
}
// printf("path_raw : %s\n", path_raw);
dfs_remove_dir();
chdir(old_path);
/*如果你想删除该目录本身的话,取消注释*/
unlink(old_path);
return 0;
}
相关文章推荐
- Linux socket 初步
- Linux Kernel 4.0 RC5 发布!
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户
- Scientific Linux 5.5 图形安装教程
- Linux 下无损图片压缩小工具介绍