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

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

  • 相关阅读:
    使用Double计算问题
    IDEA使用破解包后卸载重装或更新后无法启动问题
    GIT找出update-index --assume-unchanged关闭跟踪的文件
    GIT实现本地配置文件修改后不提交远程仓库
    git提交文件操作
    java.time.LocalDate的优点
    Eclipse中导入Maven项目pom.xml报"Unknown"错误的解决
    jsdelivr访问github资源
    java的反射机制及意义
    Oracle创建用户、表空间、视图并赋权限
  • 原文地址:https://www.cnblogs.com/pengkunfan/p/3794662.html
Copyright © 2011-2022 走看看