答案:使用std::ofstream实现日志轮转需手动控制文件开关,通过检查大小或时间戳触发轮转。1. 基本写入用std::ofstream以追加模式写日志;2. 按大小轮转在写入前判断文件尺寸,超限时重命名并创建新文件;3. 按日期轮转则每日生成独立日志文件;4. 建议封装为日志类管理状态,生产环境优先使用spdlog等成熟库。

在C++中使用
std::ofstream
ofstream
使用
std::ofstream
#include <fstream>
#include <iostream>
#include <string>
<p>void writeLog(const std::string& message) {
std::ofstream logFile("app.log", std::ios::app);
if (logFile.is_open()) {
logFile << message << "\n";
logFile.close();
} else {
std::cerr << "无法打开日志文件!\n";
}
}</p>每次写入前检查当前日志文件大小,超过阈值则重命名旧文件并创建新文件。
#include <filesystem>
#include <iostream>
<p>bool shouldRotate(const std::string& filename, size_t maxSize) {
if (!std::filesystem::exists(filename)) return false;
return std::filesystem::file_size(filename) >= maxSize;
}</p><p>void rotateLog(const std::string& filename) {
if (std::filesystem::exists(filename)) {
std::string newname = filename + ".1";
if (std::filesystem::exists(newname)) {
std::filesystem::remove(newname);
}
std::filesystem::rename(filename, newname);
}
}</p>结合写入函数:
立即学习“C++免费学习笔记(深入)”;
void writeLogWithRotation(const std::string& message,
const std::string& filename = "app.log",
size_t maxSize = 1024 * 1024) { // 1MB
if (shouldRotate(filename, maxSize)) {
rotateLog(filename);
}
std::ofstream logFile(filename, std::ios::app);
if (logFile.is_open()) {
logFile << message << "\n";
logFile.close();
}
}
根据当前日期判断是否需要轮转。例如每天生成一个日志文件:
#include <chrono>
#include <sstream>
<p>std::string getCurrentDate() {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
std::tm tm = *std::localtime(&time_t);
std::ostringstream oss;
oss << (tm.tm_year + 1900)
<< "-" << (tm.tm_mon + 1)
<< "-" << tm.tm_mday;
return oss.str();
}</p><p>void writeDailyLog(const std::string& message) {
std::string filename = "log_" + getCurrentDate() + ".txt";
std::ofstream logFile(filename, std::ios::app);
if (logFile.is_open()) {
logFile << message << "\n";
logFile.close();
}
}</p>实际项目中可以封装成一个日志类,自动管理轮转逻辑:
对于生产环境,推荐使用成熟的日志库如
spdlog
glog
基本上就这些,用
ofstream
以上就是C++如何使用ofstream实现日志轮转的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号