我想在格式struct“tm”中添加延迟,所以我运行此代码:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<limits.h>
#define SEC_PER_DAY 86400
#define SEC_PER_HR 3600
#define SEC_PER_MIN 60
int main(void) {
time_t now;
time_t time_delay;
struct tm *ts;
struct tm *ts_delay;
char buf[140];
char buf_delay[140];
now = time(NULL);
int delay =100;
ts_delay = localtime(&now);
printf("day = %d \n",ts_delay->tm_mday);
ts_delay->tm_mday += delay /SEC_PER_DAY;
printf("day = %d \n",ts_delay->tm_mday);
printf("hour = %d \n",ts_delay->tm_hour);
ts_delay->tm_hour += (delay%SEC_PER_DAY)/SEC_PER_HR;
printf("hour = %d \n",ts_delay->tm_hour);
printf("min = %d \n",ts_delay->tm_min);
ts_delay->tm_min += ((delay%SEC_PER_DAY)%SEC_PER_HR)/SEC_PER_MIN;
printf("min = %d \n",ts_delay->tm_min);
printf("sec = %d \n",ts_delay->tm_sec);
ts_delay->tm_sec += ((delay%SEC_PER_DAY)%SEC_PER_HR)%SEC_PER_MIN;
printf("sec = %d \n",ts_delay->tm_sec);
/* Format and print the time, "ddd yyyy-mm-dd hh:mm:ss zzz" */
ts = localtime(&now);
strftime(buf, sizeof(buf), "%FT%T%z", ts);
strftime(buf_delay, sizeof(buf_delay), "%FT%T%z", ts_delay);
puts(buf);
puts(buf_delay);
return 0;
}
结果:
day = 6
day = 6
hour = 4
hour = 4
min = 14
min = 15
sec = 24
sec = 64
2013-12-06T04:14:24-0600 ==> ts
2013-12-06T04:14:24-0600 ==> ts_delay
似乎延迟没有添加到ts_delay !!
任何向正确方向的推动都会非常有用thx
答案 0 :(得分:3)
您的struct tm * ts_delay
被localtime()
的号码覆盖
你有这个代码:
ts_delay = localtime(&now);
... change ts_delay;
ts = localtime(&now);
现在,localtime()
返回一个指针。因此必须分配一些存储,以便localtime的返回值可以指向somwhere有效。
运行时将在单个静态缓冲区(可能是每个线程)中为该结果分配该存储
of localtime()。因此2.调用localtime()将覆盖ts_delay
指向的相同缓冲区。
而是将localtime()的结果复制到您自己管理的存储中,而不是将struct tm
指针用于单个可用缓冲区。
struct tm ts; //not a pointer anymore
struct tm ts_delay;
ts_delay = *localtime(&now); //copy the returned struct
... change ts_delay;
ts = *localtime(&now);
如果您的平台提供,请使用getlocaltime_r
,例如
localtime_r(&now, &ts);