Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

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

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

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

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

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

Help please.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

then use timbuf perhaps by strdup-ing it.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...