localtime 和 localtime_r

来源:互联网 发布:网易公开课视频 大数据 编辑:程序博客网 时间:2024/04/30 01:40

上程序:

#include <cstdlib>#include <iostream>#include <time.h>#include <stdio.h>using namespace std;int main(int argc, char *argv[]){    time_t tNow =time(NULL);    time_t tEnd = tNow + 1800;    //注意下面两行的区别    struct tm* ptm = localtime(&tNow);    struct tm* ptmEnd = localtime(&tEnd);    char szTmp[50] = {0};    strftime(szTmp,50,"%H:%M:%S",ptm);    char szEnd[50] = {0};    strftime(szEnd,50,"%H:%M:%S",ptmEnd);        printf("%s /n",szTmp);    printf("%s /n",szEnd);        system("PAUSE");    return EXIT_SUCCESS;}

最后出来的结果是:

21:18:39

21:18:39

和最初想法不一致。

 

查阅localtime的文档,发现这段话:

This structure is statically allocated and shared by the functions gmtime and localtime. Each time either one of these functions is called the content of this structure is overwritten.

也就是说每次只能同时使用localtime()函数一次,要不就会被重写!

The localtime() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

因此localtime()不是可重入的。同时libc里提供了一个可重入版的函数localtime_r();

Unlike localtime(), the reentrant version is not required to set tzname。

修改程序:

#include <cstdlib>#include <iostream>#include <time.h>#include <stdio.h>using namespace std;int main(int argc, char *argv[]){    time_t tNow =time(NULL);    time_t tEnd = tNow + 1800;    //在这里修改程序    //struct tm* ptm = localtime(&tNow);    //struct tm* ptmEnd = localtime(&tEnd);    struct tm ptm = { 0 };    struct tm ptmEnd = { 0 };    localtime_r(&tNow, &ptm);    localtime_r(&tEnd, &ptmEnd);        char szTmp[50] = {0};    strftime(szTmp,50,"%H:%M:%S",&ptm);    char szEnd[50] = {0};    strftime(szEnd,50,"%H:%M:%S",&ptmEnd);    printf("%s /n",szTmp);    printf("%s /n",szEnd);        system("PAUSE");    return EXIT_SUCCESS;}

最后出来的结果是:

10:29:06 
10:59:06

附tm结构体:

struct tm
{
  int tm_sec;                   /* Seconds.     [0-60] (1 leap second) */
  int tm_min;                   /* Minutes.     [0-59] */
  int tm_hour;                  /* Hours.       [0-23] */
  int tm_mday;                  /* Day.         [1-31] */
  int tm_mon;                   /* Month.       [0-11] */
  int tm_year;                  /* Year - 1900.  */
  int tm_wday;                  /* Day of week. [0-6] */
  int tm_yday;                  /* Days in year.[0-365] */
  int tm_isdst;                 /* DST.         [-1/0/1]*/


#ifdef  __USE_BSD
  long int tm_gmtoff;           /* Seconds east of UTC.  */
  __const char *tm_zone;        /* Timezone abbreviation.  */
#else
  long int __tm_gmtoff;         /* Seconds east of UTC.  */
  __const char *__tm_zone;      /* Timezone abbreviation.  */
#endif
};

月份是从0月开始的。

原创粉丝点击