I'm currently working on a code that requires that I read a file which title is on a ddMMyyyyHHmm format (e.g., 060420181720.txt.) It uses the
ctime
library to get the current time and then convert it to strings.
This is the relevant snippet of my code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
string dd, MM, yyyy, HH, mm, datetime;
time_t now = time(0);
tm *ltm = localtime(&now);
a = ltm -> tm_mday;
b = 1 + ltm -> tm_mon;
c = 1900 + ltm -> tm_year;
d = ltm -> tm_hour;
e = ltm -> tm_min;
dd = to_string(a);
MM = to_string(b);
yyyy = to_string(c);
HH = to_string(d);
mm = to_string(e);
datetime = dd + MM + yyyy + HH + mm;
|
(Yes, I understand I could just write
dd = to_string(ltm -> tm_mday)
and so on but bear with me.)
There'll be times when the latest file will be unavailable, and I'll have to scan one from my files instead (say, suddenly the system goes off and
060420181720.txt
never arrives on my end so I have to make do with
060420181710.txt
or
060420181620.txt
or
060420171720.txt
). I could just reduce e, d and c by preset values I'm afraid I'd have to add in too many
if
statements and litter the code (say, if 010120190000.txt isn't available I'd have to reduce e by 10, then detect that e is negative, then make
e = e + 60
and
d = d - 1
, then detect that d is negative, then make
d = d + 24
and
c = c - 1
and so on). I've been thinking instead of getting the time since epoch, reducing it by a preset number of seconds (say,
time_since_epoch = time_since_epoch - 600
) and then converting the new time_since_epoch variable into the datetime string. Would it be possible to implement this just using the
ctime
library (or any other default one for that matter)?