如何将st_mtime(从stat函数获取)转换为string或char

我需要将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函数获取文件的时间。

请帮忙。

根据stat(2)手册页, st_mtime字段是time_t (即,在读取时间(7)手册页之后,自unix Epoch起的秒数)。

您需要localtime(3)将time_t转换为本地时间的struct tm ,然后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 it来使用它。

NB。 我使用的是localtime_r因为它更友好。

使用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" 

您可以通过另一种方式实现此目的:

  1. 声明指向tm结构的指针:

     struct tm *tm; 
  2. 声明一个适当大小的字符数组,它可以包含你想要的时间字符串:

     char file_modified_time[100]; 
  3. 使用函数localtime()st.st_mtime (其中ststat类型的struct ,即struct stat st )分解为本地时间:

     tm = localtime(&st.st_mtim); 

    注意: st_mtime是stat(2)手册页中的一个宏( #define st_mtime st_mtim.tv_sec ) 。

  4. 使用sprintf()以字符串格式或任何您希望的格式获得所需的时间:

     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:你应该用

 memset(file_modified_time, '\0', strlen(file_modified_time)); 

sprintf()之前,以避免multithreading中出现任何垃圾的风险。