一、要求:每隔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;
}