localtime 和 localtime_r 的区别
2024-10-21 03:25:07
转自:http://blog.csdn.net/maocl1983/article/details/6221810
#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 + ;
//注意下面两行的区别
struct tm* ptm = localtime(&tNow);
struct tm* ptmEnd = localtime(&tEnd); char szTmp[] = {};
strftime(szTmp,,"%H:%M:%S",ptm);
char szEnd[] = {};
strftime(szEnd,,"%H:%M:%S",ptmEnd); printf("%s /n",szTmp);
printf("%s /n",szEnd); system("PAUSE");
return EXIT_SUCCESS;
} 最后出来的结果是::: :: 和最初想法不一致。查阅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 + ; //在这里修改程序
//struct tm* ptm = localtime(&tNow);
//struct tm* ptmEnd = localtime(&tEnd);
struct tm ptm = { };
struct tm ptmEnd = { };
localtime_r(&tNow, &ptm);
localtime_r(&tEnd, &ptmEnd); char szTmp[] = {};
strftime(szTmp,,"%H:%M:%S",&ptm);
char szEnd[] = {};
strftime(szEnd,,"%H:%M:%S",&ptmEnd);
printf("%s /n",szTmp);
printf("%s /n",szEnd); system("PAUSE");
return EXIT_SUCCESS;
} 最后出来的结果是::: ::
最新文章
- checkbox、全选反选,获取值
- hdu2089 数位dp
- SQL Server被锁的表以及解锁
- java删除被占用的文件
- iOS- 利用AFNetworking3.0+(最新AFN) - 实现文件断点下载
- Chapter 1: A Simple Web Server
- JS 学习笔记--5---对象和数组
- 解决 iReport 生成 pdf 时显示不出中文的问题
- asp.net mvc源码分析-Action篇 IModelBinder
- EventDemoandStyleDemoandThemeDemo
- leetcode&mdash;Valid Parentheses
- POJ 1470 Closest Common Ancestors(LCA&;RMQ)
- Leetcode 细节实现 Set Matrix Zeroes
- 第21章 策略模式(Strategy Pattern)
- 最有用的Gulp插件汇总
- JStorm与Storm源码分析(二)--任务分配,assignment
- TensorFlow从1到2(七)线性回归模型预测汽车油耗以及训练过程优化
- PHP防CC攻击代码
- Apollo 7 — ConfigService 消息扫描设计实现
- PAT (Basic Level) Practise - 成绩排名