【问题标题】:Print time in C initially and at the end of doing sleep最初和睡眠结束时在 C 中打印时间
【发布时间】:2016-09-22 04:44:03
【问题描述】:

我正在尝试将日期打印两次:

char *init_time = getTime();
// Do something and sleep 5 seconds
char *end = getTime();
printf("train 2 started at %s and arrived at %s\n", init_time, end);

获取时间:

char* getTime(){
    time_t result;
    result = time(NULL);
    return asctime(localtime(&result));
}

为什么打印的结果一样?

【问题讨论】:

  • 一次又一次,我们让人们在提问之前不会阅读他们正在使用的功能。

标签: c date datetime time


【解决方案1】:

来自 asctime 手册页:

asctime() 函数将分解的时间值 tm 转换为 与 ctime() 格式相同的以 null 结尾的字符串。回报 value 指向一个静态分配的字符串,它可能是 被后续调用任何日期和时间函数覆盖。 asctime_r() 函数做同样的事情,但将字符串存储在 用户提供的缓冲区,应该有至少 26 个字节的空间。

换句话说,您对 asctime 的第二次调用将其结果存储在存储第一次调用结果的同一缓冲区中。

如果您想保留结果以供以后使用,请将结果复制到某处,或在获得后立即打印,或使用 asctime_r

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2021-05-29
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多