//递归删除目录和文件
int del_rf(const char* filepath)
{
struct stat64 st;
if(!stat64(filepath, &st))
{
if(S_ISREG(st.st_mode))// 删除文件
{
if(!unlink(filepath))
return 0;
else if (errno == ENOENT)
return 0;
else
{
return -1;
}
}
else if(S_ISDIR(st.st_mode))//删除目录
{
DIR* rootdir = opendir(filepath);
if(rootdir != NULL)
{
struct dirent64* ent = NULL;
union
{
struct dirent64 d;
char b[offsetof (struct dirent64, d_name) + NAME_MAX + 1];
}u;
while(readdir64_r(rootdir, &u.d, &ent) == 0 && (ent != NULL))
{
if(!strncmp(ent->d_name, ".", 2) || !strncmp(ent->d_name, "..", 3))
continue;
else
{
char filename[512] = {0};
sprintf(filename, "%s/%s", filepath, ent->d_name);
del_rf(filename);// 递归调用删除目录下的文件
}
}
closedir(rootdir);
if (!rmdir(filepath))//最后删除空目录
return 0;
else
{
return -2;
}
}
else
return -T3;
}
}
else
unlink(filepath);//文件不存在时有可能是符合链接指向的文件不存在, 也要删除
return 0;
}
int del_rf(const char* filepath)
{
struct stat64 st;
if(!stat64(filepath, &st))
{
if(S_ISREG(st.st_mode))// 删除文件
{
if(!unlink(filepath))
return 0;
else if (errno == ENOENT)
return 0;
else
{
return -1;
}
}
else if(S_ISDIR(st.st_mode))//删除目录
{
DIR* rootdir = opendir(filepath);
if(rootdir != NULL)
{
struct dirent64* ent = NULL;
union
{
struct dirent64 d;
char b[offsetof (struct dirent64, d_name) + NAME_MAX + 1];
}u;
while(readdir64_r(rootdir, &u.d, &ent) == 0 && (ent != NULL))
{
if(!strncmp(ent->d_name, ".", 2) || !strncmp(ent->d_name, "..", 3))
continue;
else
{
char filename[512] = {0};
sprintf(filename, "%s/%s", filepath, ent->d_name);
del_rf(filename);// 递归调用删除目录下的文件
}
}
closedir(rootdir);
if (!rmdir(filepath))//最后删除空目录
return 0;
else
{
return -2;
}
}
else
return -T3;
}
}
else
unlink(filepath);//文件不存在时有可能是符合链接指向的文件不存在, 也要删除
return 0;
}