Linux C++写日志
生活随笔
收集整理的這篇文章主要介紹了
Linux C++写日志
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
現在有很多成熟的日志,但用起來有點麻煩,有時候只是記錄個簡單的報錯,自己搭建了一個,根據情況自己再調整輸入的內容,當大于15KB會自動清空重寫。
#include <stdio.h> #include <dirent.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <iostream> #include <fstream> #include <sys/stat.h> using namespace std;#define DeleteRecord_C "/usr/test/DeleteRecord_C.txt" //需要寫入的日志文件路徑 #define LINE 1024//清空原文件內容 void DeleteTxt() {ofstream fileout(DeleteRecord_C, ios::trunc);//ios::trunc是清除原文件內容,可不寫,默認就是它if (!fileout) {cout << "Create file failure...\n";exit(0);}fileout.close(); }//判斷文件大小 int get_file_size() { double filesize = -1;struct stat fileInfo;if (stat(DeleteRecord_C, &fileInfo) < 0){cout << filesize << endl;return -1;}else{filesize = fileInfo.st_size;//返回的是字節 比特//cout << filesize << endl;return filesize/1024;//返回KB}} int main() { //定義命令char *rm_cmd = "rm -rf /home/C_rec_log/";//需要寫入的內容/******獲取日期******/time_t timep;struct tm *p;time(&timep);p = localtime(&timep);//獲取年//*year = 1900+(p->tm_year);//printf("year= %d\n",year);//獲取月//*month = 1+(p->tm_mon);//printf("month= %d\n",month);//將刪除命令寫入日志if (get_file_size() > 15)//15k{//日志文件大于5M(5 * 1024)后 刪除重寫DeleteTxt();}fstream f;//追加寫入,在原來基礎上加了ios::app f.open(DeleteRecord_C, ios::out | ios::app);//輸入你想寫入的內容 f << rm_cmd << endl;f.close();return 0; }總結
以上是生活随笔為你收集整理的Linux C++写日志的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python遍历目录,获取指定文件
- 下一篇: windows10设置开机自启动