Reputation: 117
I'm using stat.st_mtime
to get my last modification time of a directory and then store it into a file.txt
(stored string is something like that : 1467035651
)
Later when I retrieved data from my file.txt
, I tried to convert my string from my file.txt to int
type since the string contains just seconds but I don't know if it's a good idea to do that.
Is there any way to convert directly to time_t
?
Upvotes: 2
Views: 11663
Reputation: 70931
[Assuming C]
The strto*()
family of functions provides fail safe ways to convert a C-"string" to an integer, signed
or unsigned
, as well as to float
and double
.
Upvotes: 2
Reputation: 153498
Is there any way to convert directly to time_t?
Various other answers have posted direct solutions with strengths and weaknesses.
contains just seconds but I don't know if it's a good idea to do that.
Answer depends on the goal. IMO, it is the wrong approach
Rather than save/reading as some compiler dependent format, consider using ISO 8601 standards and save the time-stamp in a textual standard version that clearly denotes the time zone, preferable universal time.
Example C code as post is tagged C
.
For writing, something like
// Minimum size to store a ISO 8601 date/time stamp
//YYYY-MM-DDThh:mm:ss\0
#define N (4 + 5*3 + 1 + 1)
time_t x;
struct tm *tm = gmtime(&x);
if (tm == NULL) {
return failure;
}
char dest[N + 1];
int cnt = snprintf(dest, sizeof(dest), "%04d-%02d-%02dT%02d:%02d:%02dZ",
tm.tm_year + 1900, tm.tm_mon+1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
if (cnt < 0 || cnt >= sizeof(dest)) {
return failure;
}
Additional code need for fractional seconds.
Also see ftime( , , "%FT%T %z", )
.
What would you rather read in file.txt
?
1467035651
or
2016-06-27T13:54:11Z
Upvotes: 2
Reputation: 821
The function atoll
in stdlib.h
should work. Example:
time_t t;
char *time_string = //...
t = (time_t) atoll(time_string);
Upvotes: 4
Reputation: 1
According to the reference documentation time_t
is just an unspecified numeric format.
Just directly read back the numeric value from the file, there's no need for special conversions:
time_t t;
std::ifstream input("File.txt");
// ...
input >> t;
Upvotes: 7