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

后端 未结 3 1392
广开言路
广开言路 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 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.

提交回复
热议问题