C++实现常见shell命令cp mv rm mkdir

47 篇文章 2 订阅
6 篇文章 0 订阅

一般在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);
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值