I need to write files with the current date included in the name. Currently this is what I have tried:
time_t t = time(0);
struct tm * now = localtime(&t);
string date=now->tm_mday+'/'+(now->tm_mon+1)+'/'+(now->tm_year+1900);
Preferably I'd like to keep this method of getting the date as I have used it earlier on in my program.
I would use std::put_time
, something like this:
time_t t = time(0);
struct tm * now = localtime(&t);
your_file << std::put_time(now, "%d/%m/%Y");
If you mean that you need to include the date in the name of a new file, then write to a stringstream, and use your_stream.str()
to get a string containing the value.
If (though it strikes me as unlikely) you find that imposes excessive overhead, you could use strftime
instead. It writes a date/time directly to a C-style string:
char buffer[64];
strftime(buffer, sizeof(buffer), "%d/%m/%Y", now);