Ubuntu c++ 删除文件夹或者文件
废话不多说,以下代码中在Remove方法中传入文件路径即可.
//Recursively delete all the file in the directory.
int rm_dir(std::string dir_full_path) {
DIR* dirp = opendir(dir_full_path.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 sub_path = dir_full_path + '/' + dir->d_name;
if(lstat(sub_path.c_str(),&st) == -1)
{
//Log("rm_dir:lstat ",sub_path," error");
continue;
}
if(S_ISDIR(st.st_mode))
{
if(rm_dir(sub_path) == -1) // 如果是目录文件,递归删除
{
closedir(dirp);
return -1;
}
rmdir(sub_path.c_str());
}
else if(S_ISREG(st.st_mode))
{
unlink(sub_path.c_str()); // 如果是普通文件,则unlink
}
else
{
//Log("rm_dir:st_mode ",sub_path," error");
continue;
}
}
if(rmdir(dir_full_path.c_str()) == -1)//delete dir itself.
{
closedir(dirp);
return -1;
}
closedir(dirp);
return 0;
}
//Remove files or dirs
bool Remove(std::string file_name) {
std::string file_path = file_name;
struct stat st;
if (lstat(file_path.c_str(),&st) == -1) {
return EXIT_FAILURE;
}
if (S_ISREG(st.st_mode)) {
if (unlink(file_path.c_str()) == -1) {
return EXIT_FAILURE;
}
}
else if(S_ISDIR(st.st_mode)) {
if(file_name == "." || file_name == "..") {
return EXIT_FAILURE;
}
if(rm_dir(file_path) == -1)//delete all the files in dir.
{
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
还没有评论,来说两句吧...