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

后端 未结 3 1370
广开言路
广开言路 2021-01-04 19:41

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

相关标签:
3条回答
  • 2021-01-04 19:56

    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"
    
    0 讨论(0)
  • 2021-01-04 20:02

    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.

    0 讨论(0)
  • 2021-01-04 20:05

    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.

    0 讨论(0)
提交回复
热议问题