需求是想实现一个删除文件或目录的功能,类似于 rm -rf 的功能,但我们知道的删除函数如unlink,remove,rmdir都不能删除非空目录,而如果使用system()来实现会开多余的进程,消耗多余的资源,所以尽量不要使用system()函数。需要写一个函数实现,借用这位博主的代码实现这个功能。转自:http://www.cnblogs.com/StartoverX/p/4600866.html
int RmDir(std::string DirFullPath)
{
DIR* dirp = opendir(DirFullPath.c_str());
if(!dirp)
{
return -1;
}
struct dirent *dir;
struct stat st;
while((dir = readdir(dirp)) != NULL)
{
if(strcmp(dir->d_name,".") == 0
|| strcmp(dir->d_name,"..") == 0)
{
continue;
}
std::string SubPath = DirFullPath + '/' + dir->d_name;
if(lstat(SubPath.c_str(),&st) == -1)
{
printf("RmDir:lstat %s error\n",SubPath.c_str());
continue;
}
if(S_ISDIR(st.st_mode))
{
if(RmDir(SubPath) == -1) // 如果是目录文件,递归删除
{
closedir(dirp);
return -1;
}
rmdir(SubPath.c_str());
}
else if(S_ISREG(st.st_mode))
{
unlink(SubPath.c_str()); // 如果是普通文件,则unlink
}
else
{
printf("RmDir:st_mode %s error ",SubPath.c_str());
continue;
}
}
if(rmdir(DirFullPath.c_str()) == -1)//delete dir itself.
{
closedir(dirp);
return -1;
}
closedir(dirp);
return 0;
}
int rm(std::string FileName)
{
std::string FilePath = FileName;
struct stat st;
if(lstat(FilePath.c_str(),&st) == -1)
{
return -1;
}
if(S_ISREG(st.st_mode))
{
if(unlink(FilePath.c_str()) == -1)
{
return -1;
}
}
else if(S_ISDIR(st.st_mode))
{
if(FileName == "." || FileName == "..")
{
return -1;
}
if(RmDir(FilePath) == -1)//delete all the files in dir.
{
return -1;
}
}
return 0;
}
1965

被折叠的 条评论
为什么被折叠?



