Linux下 C++ 仿rm命令
```
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <algorithm>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <string>
#include <sys/stat.h>
#include <cstdio>
using namespace std;
int unlink(const char *pathname);
int rmdir(const char *pathname);
//进行文件夹删除
int rm_dir(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)
{
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
{
continue;
}
}
if(rmdir(dir_full_path.c_str()) == -1)//
{
closedir(dirp);
return -1;
}
closedir(dirp);
return 0;
}
//进行文件删除
int rm(string file_name)
{
string file_path = file_name;
struct stat st;
if(lstat(file_path.c_str(),&st) == -1)
{
return -1;
}
if(S_ISREG(st.st_mode))
{
if(unlink(file_path.c_str()) == -1)
{
return -1;
}
}
else if(S_ISDIR(st.st_mode))
{
if(file_name == "." || file_name == "..")
{
return -1;
}
if(rm_dir(file_path) == -1)//删除文件夹下所有文件
{
return -1;
}
}
return 0;
}
//去掉首尾空格
void trim(string &s)
{
if( !s.empty() )
{
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
}
}
int main(){
string code;
cout<<"home@user:rm ";
cin>>(code);
trim(code);//过滤
string dir_full_path="./"+code;
if(rm_dir(dir_full_path) != 0){
if(rm(dir_full_path) != 0){
cout<<"目录或者文件不存在";
}else{
cout<<"文件删除成功";
}
}else{
cout<<"文件夹删除成功";
}
}
```
## [ Linux C/C++ ----目录文件的操作(opendir,readdir,closedir)](https://www.cnblogs.com/wangduo/p/5858949.html)
https://blog.csdn.net/nuptwanglei/article/details/43051643
##
## [C++中的c_str()函数用法](https://www.cnblogs.com/wangduo/p/5858949.html)
https://www.cnblogs.com/wangduo/p/5858949.html
##
## [关于C++中如何判断文件、目录存在的若干方法](https://blog.csdn.net/chinawangfei/article/details/42487839)
https://blog.csdn.net/chinawangfei/article/details/42487839
##
## [c++空格处理](https://www.cnblogs.com/Shirlies/p/4666744.html)
https://www.cnblogs.com/Shirlies/p/4666744.html
##
## [rm命令参考文件](https://www.cnblogs.com/StartoverX/tag/c%2B%2B/)
https://www.cnblogs.com/StartoverX/tag/c%2B%2B/