This page:
This page is applicable to Microsoft VC++ 6. It does not use MFC.
Why use a log file?
Useful when developing, so you can see whats going on at different times, without throwing up message boxes and outputting to the screen etc. All
the
messages are in order.
How to do it
Here is how to add a function to your program to call everytime you have a message u want to record.
Add a function like this to your program.
void AddLog( char *StringToAdd )
{
FILE *LogHandle;
time_t NowTime;
char DisplayString[MAX_LOADSTRING];
LogHandle = fopen( "c:\\temp\\myprog.log" , "a+b" );
if ( LogHandle )
{
NowTime = time(NULL); // Sets NowTime to the current time from windows clock)
wsprintf( DisplayString , "[%s] %s" , ctime( &NowTime ) , StringToAdd );
// get rid of \n for time display
DisplayString[ 25 ] = ' ';
fwrite( DisplayString , sizeof(char) , lstrlen( DisplayString ) , LogHandle );
fwrite( "\r\n" , sizeof(char) , 2, LogHandle ); // adds a carriage return
fclose( LogHandle );
}
}
You have to declare the function at the top of the program too, underneath the variable declarations.
Also #include < time.h > at the top.
void AddLog( char *StringToAdd )
Anywhere in your program now, you can call this, and add some text to the logfile, which will be saved in c:\temp\myprog.log. Its a text file, so can be
viewed with notepad. If the file doesn't exist it will be created.
AddLog( "blah" );
Will make a line in the log file like:
[Mon Mar 04 22:49:43 2002 ] blah
Use the wsprinf(....) command to add variables and stuff in the log file. E.g.
wsprintf( TempText, "Program has entered the Calculate function. Integer Y= %d, Y);
AddLog( TempText );
Of course you need to declare TempText (e.g. char[60] TempText) at the top of your program, but it basically takes the second part of wsprintf and puts it in TempText. The third parameter of wsprintf, 'Y', will basically take the value in Y and put it in the string in place of the %d. AddLog(..) then sends the contents of TempText to the AddLog function.
Finally, if you have several .cpp files in your project, to add to the logfile using the same function, from another of those .cpp files, just add the
line at the top of the file like this:
extern void AddLog( char *StringToAdd );
That means the same as the declaration of the function above, but the 'extern' just means the function is in another file.
|