问题
I need to convert st_mtime to string format for passing it to java layer, i try to use this example http://www.cplusplus.com/forum/unices/10342/ but compiler produce errors
invalid conversion from 'long unsigned int*' to 'const time_t* {aka long int const*}'
initializing argument 1 of 'tm* localtime(const time_t*)' [-fpermissive]
What i doing wrong, how to get time creation of file using stat function in string presentation.
Help please.
回答1:
According to the stat(2) man page, the st_mtime
field is a time_t
(i.e. after reading the time(7) man page, a number of seconds since the unix Epoch).
You need localtime(3) to convert that time_t
to a struct tm
in local time, then, strftime(3) to convert it to a char*
string.
So you could code something like:
time_t t = mystat.st_mtime;
struct tm lt;
localtime_r(&t, <);
char timbuf[80];
strftime(timbuf, sizeof(timbuf), "%c", <);
then use timbuf
perhaps by strdup
-ing it.
NB. I am using localtime_r
because it is more thread friendly.
回答2:
use strftime()
there's an example in the man page something like:
struct tm *tm;
char buf[200];
/* convert time_t to broken-down time representation */
tm = localtime(&t);
/* format time days.month.year hour:minute:seconds */
strftime(buf, sizeof(buf), "%d.%m.%Y %H:%M:%S", tm);
printf("%s\n", buf);
Would print the output:
"24.11.2012 17:04:33"
回答3:
You can achieve this in an alternative way:
Declare a pointer to a
tm
structure:struct tm *tm;
Declare a character array of proper size, which can contain the time string you want:
char file_modified_time[100];
Break the
st.st_mtime
(wherest
is astruct
of typestat
, i.e.struct stat st
) into a local time using the functionlocaltime()
:tm = localtime(&st.st_mtim);
Note:
st_mtime
is a macro (#define st_mtime st_mtim.tv_sec
) in the man page of stat(2).Use
sprintf()
to get the desired time in string format or whatever the format you'd like:sprintf(file_modified_time, "%d_%d.%d.%d_%d:%d:%d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
NB: You should use
memset(file_modified_time, '\0', strlen(file_modified_time));
before sprintf()
to avoid the risk of any garbage which arises in multi-threading.
来源:https://stackoverflow.com/questions/13542345/how-to-convert-st-mtime-which-get-from-stat-function-to-string-or-char