[Qt] 软件自动删除旧文件

需求:工业检测应用中,需要大量的图片进行处理和存储到本地,因此抛弃旧的图片文件非常重要,否则磁盘会存满导致软件错误。

void DsStorage::CleanOldFile(std::string std_path, unsigned int rest) {
  auto count_src = std::count(std_path.begin(), std_path.end(), '/');
  QString path = QString(std_path.c_str());
  dir_ = QDir(path);

  time_t tt = time(nullptr);
  tm *t = localtime(&tt);
  auto year_num = t->tm_year + 1900;
  QString year = QString::number(year_num);
  QString today = QString(get_current_day().c_str());

  QDirIterator it(path, QDir::Dirs | QDir::NoDotAndDotDot,
                  QDirIterator::Subdirectories);
  std::vector<QString> sub_dir;
  while (it.hasNext()) {
    it.next();
    auto base = it.fileInfo().baseName();
    auto ab_path = it.fileInfo().absoluteFilePath().toStdString();
    auto deep = std::count(ab_path.begin(), ab_path.end(), '/') - count_src;
    if (!QString::compare(base, today, Qt::CaseInsensitive) || 1 != deep)
      continue;
    if (0 == base.indexOf(year)) {
      sub_dir.emplace_back(it.fileInfo().absoluteFilePath());
    }
  }

  if (sub_dir.size() <= rest) return;
  for (int i = 0; i < sub_dir.size() - rest; i++) {
    QString path = sub_dir[i];
    // remove_directory(path);
    qDebug() << "Clean old directory: " << path;
    QDir dir;
    dir.setPath(path);
    dir.removeRecursively();
  }
}

遍历文件夹下的子文件夹,然后删除掉多余的子文件夹。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值