如何将 st_mtime(从 stat 函数获取)转换为字符串或字符 [英] How to convert st_mtime (which get from stat function) to string or char

查看:76
本文介绍了如何将 st_mtime(从 stat 函数获取)转换为字符串或字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

从long unsigned int*"到const time_t*"的无效转换{akalong int const*}'

invalid conversion from 'long unsigned int*' to 'const time_t* {aka long int const*}'

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

initializing argument 1 of 'tm* localtime(const time_t*)' [-fpermissive]

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

What i doing wrong, how to get time creation of file using stat function in string presentation.

请帮忙.

推荐答案

根据stat(2) 手册页,st_mtime 字段是一个time_t(即在阅读time(7) 手册页,几秒后unix 时代).

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

你需要 localtime(3) 以本地时间将该 time_t 转换为 struct tm,然后 strftime(3) 将其转换为 char* 字符串.

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

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

then use timbuf perhaps by strdup-ing it.

注意.我使用 localtime_r 因为它对线程更友好.

NB. I am using localtime_r because it is more thread friendly.

这篇关于如何将 st_mtime(从 stat 函数获取)转换为字符串或字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆