How to convert st_mtime (which get from stat function) to string or char

落爺英雄遲暮 提交于 2019-11-30 02:48:20

问题


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, &lt);
char timbuf[80];
strftime(timbuf, sizeof(timbuf), "%c", &lt);

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:

  1. Declare a pointer to a tm structure:

    struct tm *tm;
    
  2. Declare a character array of proper size, which can contain the time string you want:

    char file_modified_time[100];
    
  3. Break the st.st_mtime (where st is a struct of type stat, i.e. struct stat st) into a local time using the function localtime():

    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).

  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!