参考链接:cout重定向到文件(转)
关于如何将cout的内容输出到文件一直不知怎么处理,在学习了该文章后,实现了我想要的功能。
代码贴出如下:
Log.h:
#ifndef LOG_H
#define LOG_H
#include<ctime>
#include<fstream>
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
class Log{
ofstream of;
struct tm* nowtime;
time_t now;
string loginfo;
streambuf* fileBuf;
int year;
int mon;
int day;
int hour;
int min;
int sec;
stringstream itos;
string s_time;
const char* logname;
public:
log(const string& str,const char* log_name);
~Log();
void getTime();
ofstream& Debug();
};
#endif
Log.cpp:
#include "Log.h"
Log::Log(const string& str,const char* log_name):loginfo(str),
logname(log_name){
of.open(logname,ios::app);
fileBuf = of.rdbuf();
getTime();
cout.rdbuf(fileBuf);
cout<<s_time<<"||"<<loginfo<<"||\t---------Log Begin----------"<<endl;
of.flush();
}
void getTime(){
time(&now);
nowtime = localtime(&now);
year = nowtime->tm_year + 1900;
mon = nowtime->tm_mon + 1;
day = nowtime->tm_mday;
hour = nowtime->tm_hour;
min = nowtime->tm_min;
sec = nowtime->tm_sec;
itos << year << "-" << mon << "-" << day
<< "," <<hour<<":"<<min<<":"<<sec;
itos >> s_time;
}
ofstream& Log::Debug(){
getTime();
cout<<s_time<<"||"<<loginfo<<"||DEBUG||\t";
of.flush();
return of;
}
Log::~Log(){
of.close();
}