This is my code:
int main()
{
time_t time1, time2;
struct tm *timeinfo1, *timeinfo2;
char *time1str, *time2str;
time1 = 3600;
time2 = 3720;
// here i must insert function from time.h
///////////////////////////
timeinfo1 = localtime(&time1);// here
localtime(&time2);
time1str = new char [strlen(asctime(timeinfo1)) + 2];
strcpy(time1str, asctime(timeinfo1));
timeinfo2 = localtime(&time2);
time2str = asctime(timeinfo2);
puts(time1str);
puts(time2str);
getchar();
return 0;
}
Is there any function that i can insert between slash comments to set internal buffer.? This buffer erase my previous value.
Yes, there is. What you're looking for is the reentrant version of localtime()
: localtime_r()
. It works exactly like localtime()
, except it writes its results into a buffer you supply as an argument instead of to a static buffer. The prototype is:
struct tm *
localtime_r(const time_t *clock, struct tm *result);
Usage in your application would look like:
struct tm timeinfo1, timeinfo2;
...
localtime_r(&time1, &timeinfo1);
localtime_r(&time2, &timeinfo2);
Since you tagged your question with C only. In C including C99 there was no such function. C11 now has a function localtime_s
that is part of the optional bounds checking extension:
struct tm *localtime_s(const time_t * restrict timer, struct tm * restrict result);
Unfortunately, there are not many platforms that implement that extension yet.
POSIX has a localtime_r
function with exactly the same interface and similar semantics. To capture this kind of system and remain portable you could do something like
#ifdef _XOPEN_SOURCE
# define localtime_s localtime_r
#endif
or if you want to have it closer to the additional guarantees that localtime_s
is supposed to give
#ifdef _XOPEN_SOURCE
struct tm *localtime_s(const time_t * restrict timer, struct tm * restrict result) {
return (timer && result ? localtime_r(timer, result) : 0);
}
#endif
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.