zoukankan      html  css  js  c++  java
  • localtime 和 localtime_r

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

    上程序:

    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

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

  • 相关阅读:
    选择器
    asp.net 操作ftp类
    女装类视觉设计感悟
    跨域读取js变色
    关于jQuery的ajax初级应用
    打造前端自动化编译环境(思路)
    <base>标签在ie6下的问题
    通过压缩图片 来提升页面加载速度
    原来我一直不懂cookie
    去处浏览器的默认效果(autocomplete, outline)
  • 原文地址:https://www.cnblogs.com/pengkunfan/p/3794662.html
Copyright © 2011-2022 走看看