The difference between localtime and Localtime_r

Source: Internet
Author: User

Turn from: http://blog.csdn.net/maocl1983/article/details/6221810#include <cstdlib>#include<iostream>#include<time.h>#include<stdio.h>using namespacestd;intMainintargcChar*argv[]) {time_t Tnow=Time (NULL); time_t tEnd= Tnow +1800; //Note the difference between the following two lines    structtm* PTM = localtime (&Tnow); structtm* ptmend = localtime (&tEnd); Charsztmp[ -] = {0}; Strftime (Sztmp, -,"%h:%m:%s", PTM); Charszend[ -] = {0}; Strftime (Szend, -,"%h:%m:%s", Ptmend); printf ("%s/n", sztmp); printf ("%s/n", Szend); System ("PAUSE"); returnexit_success;} The final result is: +: -: the  +: -: theInconsistent with the original idea. Check the localtime documentation to find this passage: this structure isStatically allocated and shared by the functions Gmtime and localtime. Each time either one of these functions isCalled the content of ThisStructure isoverwritten. That means you can only use the localtime () function once at a time, or it will be rewritten! The localtime () function need not be reentrant. A function that isNot required to be reentrant isNot required to is thread-safe. So localtime () is not reentrant. At the same time LIBC provides a reentrant version of the function Localtime_r (); unlike localtime (), the reentrant version isNot required toSetTzname. Modify Program: #include<cstdlib>#include<iostream>#include<time.h>#include<stdio.h>using namespacestd;intMainintargcChar*argv[]) {time_t Tnow=Time (NULL); time_t tEnd= Tnow +1800; //Modify the program here//struct tm* ptm = localtime (&tnow); //struct tm* ptmend = localtime (&tend);    structTM PTM = {0 }; structTM Ptmend = {0 }; Localtime_r (&tnow, &PTM); Localtime_r (&tend, &ptmend); Charsztmp[ -] = {0}; Strftime (Sztmp, -,"%h:%m:%s",&PTM); Charszend[ -] = {0}; Strftime (Szend, -,"%h:%m:%s",&ptmend); printf ("%s/n", sztmp); printf ("%s/n", Szend); System ("PAUSE"); returnexit_success;} The final result is:Ten: in: .  Ten: -: .  

The difference between localtime and Localtime_r

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.