c++ - 如何使用 C++ 不使用 system() 删除除最后 10 个文件之外的所有文件

标签 c++ linux

如何在不使用 system() 的情况下实现 system("ls -t1 . | tail -n +11 | xargs rm -rf")。我只想在我的 linux 文件夹中保留最新的 10 个文件,当我调用 C++ 函数时,其余的文件应该被删除。

最佳答案

这里有一些 C++ 代码,不需要存储所有条目,而只是记住最旧的 10 个条目并删除较新的条目。

与删除文件的代码一样请小心,如果运行以下代码,它将删除文件

#include <filesystem>
#include <vector>
#include <queue>
#include <iostream>

namespace fs = std::filesystem;
using pathvec = std::vector<fs::directory_entry>;

struct newer_file {
    bool operator()(const fs::directory_entry& p, const fs::directory_entry& p2)
    {
        return p.last_write_time() < p2.last_write_time();
    }
};

void delete_newest(fs::path directory, int keep_n = 10)
{
    //store N oldest entries, delete any that are newer
    std::priority_queue<fs::directory_entry, pathvec, newer_file> oldestN;
    for (auto entry : fs::directory_iterator(directory))
    {
        oldestN.push(entry);
        if (oldestN.size() > keep_n)
        {
            //careful, recursive delete
            fs::remove_all(oldestN.top());
            oldestN.pop();
        }
    }
}

int main(int argc, const char** argv)
{
    if (argc < 2)
    {
        std::cout << "argument needed" << std::endl;
        return -1;
    }
    delete_newest(fs::path(argv[1]));
    return 0;
}

关于c++ - 如何使用 C++ 不使用 system() 删除除最后 10 个文件之外的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54751321/

相关文章:

c++ - 如何使用OpenCV测试框架来运行特定的测试?

c++ - C 风格字符串和 C++ 中的动态分配

linux - 一个进程占用多少核?

linux - 如何知道连接被拒绝抛出了 curl

c++ - 在 Linux 上启用 Unicode 16

c++ - Linux 系统的有限插件架构?

c++ - 具有原子状态的单例模式

c++ - 带有 SURF 的 OpenCV C++ 'Access Violation'

c++ - 在 GCC、Clang 和 MSVC 中,有什么方法可以符合 C++98 而不是 C++03 吗?

c++ - 错误系统:9:错误的文件描述符 (BOOST::FileSystem)