码迷,mamicode.com
首页 > 其他好文 > 详细

localtime 和 localtime_r

时间:2014-06-28 20:08:01      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   strong   

---恢复内容开始---

 

上程序:

  1. #include <cstdlib>  
  2. #include <iostream>  
  3. #include <time.h>  
  4. #include <stdio.h>   
  5.   
  6. using namespace std;  
  7.   
  8. int main(int argc, char *argv[])  
  9. {  
  10.     time_t tNow =time(NULL);  
  11.     time_t tEnd = tNow + 1800;  
  12.     //注意下面两行的区别   
  13.     struct tm* ptm = localtime(&tNow);  
  14.     struct tm* ptmEnd = localtime(&tEnd);  
  15.   
  16.     char szTmp[50] = {0};  
  17.     strftime(szTmp,50,"%H:%M:%S",ptm);  
  18.     char szEnd[50] = {0};  
  19.     strftime(szEnd,50,"%H:%M:%S",ptmEnd);  
  20.       
  21.   
  22.     printf("%s /n",szTmp);  
  23.     printf("%s /n",szEnd);  
  24.       
  25.   
  26.     system("PAUSE");  
  27.     return EXIT_SUCCESS;  
  28. }  

 

最后出来的结果是:

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。

 

修改程序:

  1. #include <cstdlib>  
  2. #include <iostream>  
  3. #include <time.h>  
  4. #include <stdio.h>   
  5.   
  6. using namespace std;  
  7.   
  8. int main(int argc, char *argv[])  
  9. {  
  10.     time_t tNow =time(NULL);  
  11.     time_t tEnd = tNow + 1800;  
  12.   
  13.     //在这里修改程序   
  14.     //struct tm* ptm = localtime(&tNow);   
  15.     //struct tm* ptmEnd = localtime(&tEnd);   
  16.     struct tm ptm = { 0 };  
  17.     struct tm ptmEnd = { 0 };  
  18.     localtime_r(&tNow, &ptm);  
  19.     localtime_r(&tEnd, &ptmEnd);  
  20.       
  21.     char szTmp[50] = {0};  
  22.     strftime(szTmp,50,"%H:%M:%S",&ptm);  
  23.     char szEnd[50] = {0};  
  24.     strftime(szEnd,50,"%H:%M:%S",&ptmEnd);  
  25.     printf("%s /n",szTmp);  
  26.     printf("%s /n",szEnd);  
  27.       
  28.   
  29.     system("PAUSE");  
  30.     return EXIT_SUCCESS;  
  31. }  

 

最后出来的结果是:

10:29:06
10:59:06

http://blog.csdn.net/maocl1983/article/details/6221810

 

---恢复内容结束---

localtime 和 localtime_r,布布扣,bubuko.com

localtime 和 localtime_r

标签:style   blog   http   color   使用   strong   

原文地址:http://www.cnblogs.com/pengkunfan/p/3794662.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!