1

这是我的代码:

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

我可以在斜线注释之间插入任何函数来设置内部缓冲区吗?这个缓冲区擦除了我之前的值。

4

2 回答 2

2

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
于 2013-10-26T07:33:28.860 回答
2

就在这里。您正在寻找的是localtime():的可重入版本localtime_r()。它的工作原理与 完全相同localtime(),只是它将结果写入您作为参数提供的缓冲区而不是静态缓冲区。原型是:

 struct tm *
 localtime_r(const time_t *clock, struct tm *result);

您的应用程序中的用法如下所示:

struct tm timeinfo1, timeinfo2;
...
localtime_r(&time1, &timeinfo1);
localtime_r(&time2, &timeinfo2);
于 2013-10-26T07:12:41.780 回答