log.h
#ifndef LOG_H.H
#define LOG_H.H
#include <fstream>
#include <string>
class CLLog
{
public:
CLLog();
~CLLog();
void SetFilePath(char* cFilePath);
void GetFilePath(char* cFilePath);
void Log(char* cLogString);
bool Init();
private:
std::fstream fFile;
std::string sFilePath;
std::string sContent;
};
#endif
log.cpp
#include <time.h>
#include "log.h"
#include <ios>
#include <iostream>
CLLog::CLLog()
{
sFilePath = "";
}
CLLog::~CLLog()
{
if(fFile)
{
fFile.close();
}
sFilePath = "";
}
bool CLLog::Init()
{
fFile.open(sFilePath.c_str() , std::ios::in|std::ios::out|std::ios::app);
if(!fFile)
{
std::cout<<"打開-"<<sFilePath<<"-文件失敗!"<<std::endl;
return false;
}
std::cout<<"打開文件成功!"<<std::endl;
return true;
}
void CLLog::SetFilePath(char* cFilePath)
{
sFilePath = std::string(cFilePath);
Init();
}
void CLLog::GetFilePath(char* cFilePath)
{
//strcpy(cFilePath , sFilePath.c_str());
sFilePath.copy(cFilePath , sFilePath.length(),0);
}
void CLLog::Log(char* cLogString)
{
time_t t = time(0);
char *cTmp=new char[32]();
strftime(cTmp ,32,"%Y-%m-%d %H:%M:%S",localtime(&t));
sContent = std::string(cLogString)+"/t"+std::string(cTmp) +"/t/n";
delete cTmp;
cTmp = NULL;
fFile.seekp(0,std::ios_base::end);
fFile.write(sContent.c_str() , sContent.length());
}
main.cpp
#include "log.h"
#include <iostream>
int main()
{
int i= 8;
int j = i;
CLLog log;
log.SetFilePath("log.txt");
for(int i=0;i<50;i++)
log.Log("adlkfjaldfjalsdf");
std::cout<<"safdadf"<<std::endl;
return 0;
}
編譯:
1 . g++ log.cpp main.cpp -o main
這種編譯方法不能用於GDB調試,要想調試的加上 -g
g++ -g log.cpp main.cpp -o main
2.編譯通過 可以進行調試(依次進行一下操作)
gdb main //進入調試狀態
break 6 //在main.cpp中的第6行設置斷點,
break log.cpp:37 // 在log.cpp的37行設置斷點
run 運行
停止到斷點出
print 變量 // 打印變量值
step //單步執行,可進入到函數體內
next //單步執行,但不可進入到函數體內
continue //從斷點出繼續執行
3 makefile
main:main.o log.o
g++ -o main main.o log.o //前邊一定要有一個tab鍵
log.o:log.cpp
g++ -c log.cpp -g log.cpp
main.o:main.cpp
g++ -c main.cpp -g main.cpp