我需要将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 *)'的参数1 [-fpermissive]
我做错了,如何在字符串演示中使用stat函数来创建文件的时间。
请帮助。
答案 0 :(得分:13)
根据stat(2)手册页,st_mtime
字段为time_t
(即在阅读time(7)手册页后,自{{3}以来的秒数}})。
您需要unix Epoch在当地时间将time_t
转换为struct tm
,然后localtime(3)将其转换为char*
字符串。
所以你可以编写类似的代码:
time_t t = mystat.st_mtime;
struct tm lt;
localtime_r(&t, <);
char timbuf[80];
strftime(timbuf, sizeof(timbuf), "%c", <);
然后可能timbuf
使用strdup
。
NB。我正在使用localtime_r
因为它更友好。
答案 1 :(得分:9)
使用strftime()
man page中有一个示例:
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"
答案 2 :(得分:2)
您可以通过其他方式实现此目标:
声明指向tm
结构的指针:
struct tm *tm;
声明一个大小合适的字符数组,它可以包含你想要的时间字符串:
char file_modified_time[100];
使用函数{将st.st_mtime
(其中st
struct
类型为stat
,即struct stat st
)分解为本地时间{1}}:
localtime()
注意:tm = localtime(&st.st_mtim);
是stat(2)手册页中的一个宏(st_mtime
)。
使用#define st_mtime st_mtim.tv_sec
以字符串格式或您喜欢的格式获得所需的时间:
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);
在memset(file_modified_time, '\0', strlen(file_modified_time));
之前,以避免多线程中出现任何垃圾的风险。