您的位置:首页 > 运维架构 > Linux

linux删除文件夹下所有内容

2014-06-26 15:30 811 查看
linux 下面 删除文件夹下的所有内容,忘了是在哪里找到的原型,自己又改了改,现在是完全可以用的。

//判断是否为目录
bool is_dir(const char *path)
{
struct statstatbuf;
if(lstat(path,&statbuf) ==0)
{
return S_ISDIR(statbuf.st_mode) != 0;
}
return false;
}

//判断是否为常规文件
bool is_file(const char *path)
{
struct statstatbuf;
if(lstat(path,&statbuf) ==0)
return S_ISREG(statbuf.st_mode) != 0;
return false;
}

//判断是否是特殊目录
bool is_special_dir(const char *path)
{
return strcmp(path, ".")== 0 || strcmp(path, "..") == 0;
}

//生成完整的文件路径
void get_file_path(const char *path, const char *file_name, char *file_path)
{
strcpy(file_path,path);
if(file_path[strlen(path) - 1] != '/')
strcat(file_path, "/");
strcat(file_path,file_name);
}

void delete_file(const char *path)
{
DIR *dir;
dirent *dir_info;
char file_path[PATH_MAX];
if(is_file(path))
{
remove(path);
return;
}
if(is_dir(path))
{
if((dir = opendir(path)) ==NULL)
return;
while((dir_info =readdir(dir)) != NULL)
{
if(is_special_dir(dir_info->d_name))
continue;
get_file_path(path, dir_info->d_name, file_path);
if(is_dir(file_path))
{
delete_file(file_path);
rmdir(file_path);
}
elseif(is_file(file_path))
{
remove(file_path);
}
}
closedir(dir);//关闭目录
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: