断点调试和打印日志各有优点,下面我们来简要说说如何在程序中打印日志,在BCB6.0中实现。
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include <wtypes.h> #include <stdio.h> #include <fstream> #include <string> using namespace std; #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { SYSTEMTIME stCurTime = {0}; GetLocalTime(&stCurTime); char szTime[128] = {0}; sprintf(szTime, "%d-%d-%d %d:%d:%d", stCurTime.wYear, stCurTime.wMonth, stCurTime.wDay, stCurTime.wHour, stCurTime.wMinute, stCurTime.wSecond); char szLocation[1024] = {0}; sprintf(szLocation, "Function--->%s, Line: %d, File: %s", __FUNC__, __LINE__, __FILE__); char buf[2048] = {0}; sprintf(buf, "%s %s", szTime, szLocation); ofstream outfile("log.txt", ios::app); outfile << buf << endl; } //---------------------------------------------------------------------------
结果,log.txt中为:
2013-11-9 10:42:57 Function--->TForm1::Button1Click, Line: 32, File: C:\Documents and Settings\Administrator\hLآ\bcbTest\Unit1.cpp
2013-11-9 10:42:59 Function--->TForm1::Button1Click, Line: 32, File: C:\Documents and Settings\Administrator\hLآ\bcbTest\Unit1.cpp
2013-11-9 10:43:0 Function--->TForm1::Button1Click, Line: 32, File: C:\Documents and Settings\Administrator\hLآ\bcbTest\Unit1.cpp
实际上,上述只是打印了基本的信息,后续博文中会介绍如何打印其它需要打印的信息。