根据日期和大小来删除文件

一、要求:每隔7天将日志文件AlgorithmFile.log删除

1、低版本的C++会导致 #include 无法打开,切换C++即可。
在这里插入图片描述
代码实现:

#include <chrono>
#include <ctime>
#include <fstream>
#include <filesystem>


void delLogFile()
{
    // 待删除文件路径
    std::string filePath = "AlgorithmFile.log";

    // 定义删除周期 (7天)
    //声明一个以天数为单位的 std::chrono::duration 对象
    //std::ratio<60 * 60 * 24> 表示表示一天的时间(86400 秒)
    std::chrono::duration<int, std::ratio<60 * 60 * 24>> period(7);

    // 获取当前时间
    std::time_t currTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); //返回当前系统时间的时间点

    // 获取上次删除文件的时间
    std::time_t lastTime;
    std::ifstream fileTime("lastTime.txt", std::ios::in);//以读取方式打开文件。

    //if (std::filesystem::exists("lastTime.txt") != true) //如果文件不存在
    //    std::ofstream new_file("lastTime.txt");//则创建

    //检查文件是否打开
    if (fileTime.is_open()) {
        fileTime >> lastTime;
        fileTime.close();//关闭文件流
    }
    else {
        lastTime = currTime;

        // 保存当前时间到文件中
        std::ofstream fileNewTime("lastTime.txt", std::ios::out);//以写入方式打开文件,out模式会自动创建该文件
        if (fileNewTime.is_open()) {
            fileNewTime << currTime;
            fileNewTime.close();
        }
    }

    // 计算时间差
    std::chrono::seconds diff(currTime - lastTime);

    // 删除文件
    if (diff > period && std::filesystem::exists(filePath)) {
        std::filesystem::remove(filePath);

        // 保存当前时间到文件中
        std::ofstream fileNewTime("lastTime.txt", std::ios::out);//以写入方式打开文件,out模式会自动创建该文件
        if (fileNewTime.is_open()) {
            fileNewTime << currTime;
            fileNewTime.close();
        }
    }
}

二、要求:日志文件AlgorithmFile.log的大小达到100M就将其删除

使用filesystem::file_size函数获取文件大小,并检查是否有错误发生。
1 MB = 1024 KB = 1024 * 1024 字节(Bytes)= 1024 * 1024 * 8 Bits

#include <iostream>
#include <fstream>
#include <filesystem>

int main() {
    std::string file_path = "AlgorithmLog.log"; // 请替换为你的文件路径
    std::uintmax_t max_size = 1024*1024*100; // 设置最大文件大小(例如:100M)

    std::error_code ec; // 用于捕获filesystem操作中的错误
    std::uintmax_t file_size = std::filesystem::file_size(file_path, ec);

    if(ec) { // 检查是否有错误发生
        std::cout << "Error: " << ec.message() << std::endl;
    } else {
        std::cout << "File size: " << file_size << std::endl;

        if (file_size >= max_size) {
            if (std::filesystem::remove(file_path, ec)) { // 删除文件
                std::cout << "File deleted." << std::endl;
            } else {
                std::cout << "Error deleting the file: " << ec.message() << std::endl;
            }
        } else {
            std::cout << "File size is within limits." << std::endl;
        }
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值