Hey guys. This is my first post. I began learning programming in C#, but my job occasionally requires that I maintain some legacy C++ code. This is usually a struggle for me. Nonetheless, my task is simple - create a class in a specific project that writes out a log file. This is an ATL project with no MFC support. I'm passing the function an error message and the filename without a path. Please take a look at my code and alert me if I am doing something incorrectly. The compiler is not complaining about anything, but I still feel uncomfortable with this code. Thanks in advance!
// DetailsLog.cpp : Implementation of DetailsLog
// 12/03/2007
// RA
#include "StdAfx.h"
#include "DetailsLog.h"
#include <iostream>
STDMETHODIMP DetailsLog::WriteLogEntry(CString logMsg, CString logFileName)
{
HRESULT hr = S_OK;
CString errorLogPath;
CString dateDir;
// Get the current date for the correct sub dir
SYSTEMTIME cd;
GetSystemTime(&cd);
// Build the date string
dateDir.Format("%s", cd.wYear);
dateDir.AppendFormat("%s", cd.wMonth);
dateDir.AppendFormat("%s", cd.wDay + "\\");
// Build the path to the log directory
errorLogPath.Format("%s", GetMACESSexpBasePath());
errorLogPath.AppendFormat("\\Log\\" + dateDir);
// Build the timestamp string
CString timeStamp;
timeStamp.Format("---------------- ");
timeStamp.AppendFormat("%s", cd.wHour + ":");
timeStamp.AppendFormat("%s", cd.wMinute + ":");
timeStamp.AppendFormat("%s", cd.wSecond);
timeStamp.AppendFormat(" ----------------\r\n");
try
{
// First check and see if the log dir already exists
if(!PathIsDirectory(errorLogPath))
{
// It does not already exist, so create it
CreateDirectory(errorLogPath, NULL);
}
// Now that we've checked for the directory,
// append the file name to the path
errorLogPath.AppendFormat(logFileName);
// Now write to the log file
ofstream logFile(errorLogPath);
cout << timeStamp << endl;
cout << logMsg << endl;
// Close the open stream
logFile.close();
}
catch(...)
{
return E_FAIL;
}
return hr;
}