关于将程序输出重定向到文件的实现

参考链接: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();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值