11

我需要将 st_mtime 转换为字符串格式以将其传递给 java 层,我尝试使用此示例http://www.cplusplus.com/forum/unices/10342/但编译器会产生错误

从“long unsigned int*”到“const time_t* {aka long int const*}”的无效转换

初始化 'tm* localtime(const time_t*)' [-fpermissive] 的参数 1

我做错了什么,如何在字符串表示中使用 stat 函数来创建文件的时间。

请帮忙。

4

3 回答 3

16

根据stat(2)手册页,该st_mtime字段是一个time_t(即在阅读time(7)手册页后,自unix Epoch以来的秒数)。

您需要localtime(3)将其转换time_tstruct tm本地时间的 a,然后strftime(3)将其转换为char*字符串。

所以你可以编写如下代码:

time_t t = mystat.st_mtime;
struct tm lt;
localtime_r(&t, &lt);
char timbuf[80];
strftime(timbuf, sizeof(timbuf), "%c", &lt);

然后timbuf也许通过strdup-ing 来使用它。

注意。我正在使用localtime_r它是因为它对线程更友好。

于 2012-11-24T15:01:00.583 回答
9

使用手册页strftime()中有一个示例,例如:

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

将打印输出:

"24.11.2012 17:04:33"
于 2012-11-24T15:00:10.070 回答
2

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.

于 2014-07-23T06:49:51.967 回答