一般在C++中我们可以直接用system()
函数调用shell命令,但该方式偶尔会失败,故需要在不用system()
函数实现常见的linux shell命令。如下:
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <fstream>
// copy in binary mode
bool copyFile(const char *SRC, const char* DEST)
{
std::ifstream src(SRC, std::ios::binary);
std::ofstream dest(DEST, std::ios::binary);
dest << src.rdbuf();
return src && dest;
}
// mkdir 新建文件夹
int Mkdir(const std::string &src) {
int flag = 1;
flag = mkdir(src.c_str(), S_IRWXU);
return flag;
}
// 删除文件夹,rmdir函数仅能删除空文件夹,故需要遍历删除文件夹下所有文件再删除文件夹
int RemoveDirectory(const std::string &src) {
const char *path = src.c_str();
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;
if (d) {
struct dirent *p;
r = 0;
while (!r && (p = readdir(d))) {
int r2 = -1;
char *buf;
size_t len;
/* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue;
len = path_len + strlen(p->d_name) + 2;
buf = (char *)malloc(len * sizeof(char));
if (buf) {
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf)) {
if (S_ISDIR(statbuf.st_mode))
r2 = RemoveDirectory(buf);
else
r2 = unlink(buf);
}
free(buf);
}
r = r2;
}
closedir(d);
}
if (!r) r = rmdir(path);
return r;
}
// 重命名,参数可以是两个文件夹名,也可以是两个文件名,但不能是一个文件夹一个文件
int RenameDir(const std::string &oldname, const std::string &newname) {
int flag = 1;
flag = rename(oldname.c_str(), newname.c_str());
return flag;
}
//判断是否是文件夹
int JudgeDir(const char *path) {
struct stat s;
stat(path, &s);
return S_ISDIR(s.st_mode);
}