localtime 和 localtime_r 的区别
2015-11-24 11:34
274 查看
转自: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 + 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
相关文章推荐
- 记录一下接多盟SDK遇到的问题
- 文件及目录操作命令
- Github项目解析(一)-->上传Android项目至github
- springmvc 和struts2的区别
- Leetcode Fraction to Recurring Decimal
- POI实现excel导入
- 进程与线程
- Servlet:下载文件
- 查看文件及内容处理命令
- 查一个表中某个字段相同的其他所有用户信息
- mysql1130远程连接没有权限的解决方法
- pthread_create
- VFL语言简洁
- hbase建索引的两种方式
- HttpClient+List<NameValuePair>发送和接收参数——基于struts2或者ssh等框架
- 文件压缩及解压缩命令
- 框架:关闭多个activity的方案之一(用list记录create过的activity)
- opencv2.4.9中期望最大(EM)算法理解
- IOS7、8模态半透明弹出框
- HTML中<script ...>....</script>标签的正则表达式?