M
Marcus Kwok
I have a simple LogFile class that I use to log messages, and each
message has the current date and time prepended to the message.
Currently, I am using strftime() to format the date, and placing the
result into a character array. Of course, there is now the issue of
whether the length of the string is longer than the character array.
Is there an equivalent way to do this so that it is more C++-like? For
example, something that will place the result into a std::string or
something, so I don't have to worry about if timeStringLength will be
large enough.
void LogFile::logEntry(const char* message)
{
// Output date and time in ISO 8601:2004 format, i.e., YYYY-MM-DD HH:MM:SS
const char* timeStringFormat = "%Y-%m-%d %H:%M:%S";
const int timeStringLength = 20;
char timeString[timeStringLength];
// get current date and time
time_t t = time(0);
tm *curTime = localtime(&t);
strftime(timeString, timeStringLength, timeStringFormat, curTime);
logFile << timeString << '\t' << message << '\n';
flush(logFile);
}
message has the current date and time prepended to the message.
Currently, I am using strftime() to format the date, and placing the
result into a character array. Of course, there is now the issue of
whether the length of the string is longer than the character array.
Is there an equivalent way to do this so that it is more C++-like? For
example, something that will place the result into a std::string or
something, so I don't have to worry about if timeStringLength will be
large enough.
void LogFile::logEntry(const char* message)
{
// Output date and time in ISO 8601:2004 format, i.e., YYYY-MM-DD HH:MM:SS
const char* timeStringFormat = "%Y-%m-%d %H:%M:%S";
const int timeStringLength = 20;
char timeString[timeStringLength];
// get current date and time
time_t t = time(0);
tm *curTime = localtime(&t);
strftime(timeString, timeStringLength, timeStringFormat, curTime);
logFile << timeString << '\t' << message << '\n';
flush(logFile);
}