#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <stdio.h>
class FLOG
{
public:
FLOG(); //类的构造函数
~FLOG(); //类的析构函数
BOOL write(std::string data); //写入函数
BOOL write(std::string data, std::string data1); //写入函数的重载
BOOL write(std::string data, std::string data1, std::string data2); //写入函数的重载
private:
SYSTEMTIME time;
std::ofstream out;
char *filename;
char *buff;
BOOL rejet;
};
FLOG::FLOG()
{
GetLocalTime(&time); //获取当前时间
filename = new char[sizeof(char)* 200];
buff = new char[sizeof(char)* 200];
sprintf_s(filename, 200, "%d-%d-%d.log", time.wYear, time.wMonth, time.wDay); //格式化时间字符串
out.open(filename, std::ios::app); //以当前时间为名打开一个LOG文件
if (out.is_open()) //如果文件打开成功,设置REJET为真,否则为假
{
rejet = TRUE;
}
else
{
rejet = FALSE;
}
}
FLOG::~FLOG()
{
delete(filename); //释放FILENAME
delete(buff); //释放BUFF
out.close(); //关闭文件句柄
}
BOOL FLOG::write(std::string data)
{
if (rejet) //如果REJET为真 则写入数据到文件
{
int i;
GetLocalTime(&time);
i = sprintf_s(buff, 200, "%d-%d-%d %d:%d:%d\t", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
out.write(buff, i);
out.write(data.c_str(), data.length());
return TRUE;
}
else
{
return FALSE;
}
}
BOOL FLOG::write(std::string data, std::string data1)
{
if (rejet)
{
int i;
GetLocalTime(&time);
i = sprintf_s(buff, 200, "%d-%d-%d %d:%d:%d\t", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
out.write(buff, i);
out.write(data.c_str(), data.length());
out.write(data1.c_str(), data1.length());
return TRUE;
}
else
{
return FALSE;
}
}
BOOL FLOG::write(std::string data, std::string data1, std::string data2)
{
if (rejet)
{
int i;
GetLocalTime(&time);
i = sprintf_s(buff, 200, "%d-%d-%d %d:%d:%d\t", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
out.write(buff, i);
out.write(data.c_str(), data.length());
out.write(data1.c_str(), data1.length());
out.write(data2.c_str(), data2.length());
return TRUE;
}
else
{
return FALSE;
}
}
void main()
{
FLOG flog;
while (1)
{
flog.write("123", "\n");
Sleep(1000); //在VS2013平台下面选择使用静态MFC编译 发现LOG文件不会有任何写入,空白一片,
//把Sleep(1000) 这个注释掉 LOG文件写入正常。
//把静态MFC编译选项改成使用标准WINDOWS库的情次下。LOG文件写入正常
} //实在是想不出来是为什么 只能来论坛找大神求解!!!
}