gpt4 book ai didi

c - 添加延迟到时间格式结构 "tm"

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:05 28 4
gpt4 key购买 nike

我想在格式结构“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

最佳答案

您的 struct tm * ts_delay 被 2. 对 localtime() 的调用覆盖你有这个代码:

ts_delay = localtime(&now);
... change ts_delay;
ts = localtime(&now);

现在,localtime() 返回一个指针。所以必须分配一些存储空间,以便 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);

关于c - 添加延迟到时间格式结构 "tm",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20421579/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com