c++輸出日志文件
代碼如下
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include <thread>
int main()
{
// 定義文件路徑,需要注意文件夾/home/wljss/my_log需要存在否則會(huì)報(bào)錯(cuò)
std::string filePath = "/home/wljss/my_log/datalog";
std::cout<<filePath<<std::endl;
// 創(chuàng)建并打開文件,以追加模式(std::ios_base::app)打開文件;后面可以用outFile.open()來打開別的文件
std::ofstream outFile(filePath, std::ios_base::app);
// 檢查文件是否成功打開
if (!outFile.is_open()) {
std::cout << "無法打開文件: " << filePath << std::endl;
return 1;
}
// 模擬不斷追加寫入數(shù)據(jù)
for(int i=1;i<=5;++i)
{
// 獲取當(dāng)前時(shí)間戳
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::cout << "當(dāng)前時(shí)間: " << std::ctime(&in_time_t);
// 生成一些示例日志數(shù)據(jù)
std::string logData = "日志數(shù)據(jù): " + std::to_string(rand() % 1000) + "\n";
// 寫入數(shù)據(jù)到文件
outFile << logData;
// 刷新輸出緩沖區(qū),確保數(shù)據(jù)寫入文件
outFile.flush();
// 等待一段時(shí)間(例如1秒),然后再次寫入
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// 關(guān)閉文件
outFile.close();
return 0;
}
上面需要注意,如果沒有文件夾/home/wljss/my_log會(huì)報(bào)錯(cuò),可以用下面的方法創(chuàng)建文件夾
//linux系統(tǒng)
#include <unistd.h>
std::string folderPath="/home/wljss/my_log";
if (access(folderPath.c_str(), 0) == -1)
{
system(("mkdir -p "+folderPath).c_str());
}

浙公網(wǎng)安備 33010602011771號(hào)