c - 最初和 sleep 结束时在 C 中打印时间

标签 c date datetime time

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

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));
}

为什么打印的结果一样?

最佳答案

来自 asctime 手册页:

The asctime() function converts the broken-down time value tm into a null-terminated string with the same format as ctime(). The return value points to a statically allocated string which might be overwritten by subsequent calls to any of the date and time functions. The asctime_r() function does the same, but stores the string in a user-supplied buffer which should have room for at least 26 bytes.

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

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

关于c - 最初和 sleep 结束时在 C 中打印时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37422556/

相关文章:

c# - 如何使用非托管导出 (Robert Giesecke) 将 dateTime 类型数组从 .NET 传递到 Delphi?

php - 之后我必须用 DateTimeZone 显式覆盖 PHP 的 DateTime 吗?

c - 我是否需要为每个 C POSIX 线程使用不同的签名集以确保屏蔽信号时的原子性?

ruby-on-rails - Rails Date.today 反射(reflect)了服务器部署日期

date - Flutter/Dart : DateTime. fromMillisecondsSinceEpoch 返回不正确的时间

ios - 手动设置日期以使日期选择器始终返回一个日期

c - 如何禁用 Windows 7 上的开始按钮(而不是任务栏)?

处理 stdout 的并发问题

c - 在 libcoap coap 服务器 GET 响应处理程序中如何访问 URI 的查询添加项?

python - 如何根据日期时间值获取最近的 json 对象?