c - 在 C 编程中存储系统调用

标签 c datetime

我有一个 C 程序,它使用以下行将时间戳打印为字符串:

sprintf (scratch_buffer, "%s\0", dfr_time_date_strg);

此时间戳始终打印为 UTC,但我想添加调用字符串 date +%zdate +%Z

两个时区值可以这样调用:

system("date +%z");
system("date +%Z");

但是我如何将它们分配给名为 tz_offsettz_namechar 字符串,以便最终的时间戳打印行是:

sprintf (scratch_buffer, "%s %s (%s)\0", dfr_time_date_strg, tz_offset, tz_name);

最佳答案

首先,您描述为“系统调用”的东西不是系统调用,只是对system() 函数的调用。系统调用是 something different .

关于您的问题:您有一个 stereotypical XY problem . 您绝对不想获取 date 命令的输出。(That could be done using popen(),但请不要。)您更想使用标准库:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    char buf[256];
    strftime(buf, sizeof buf, "%Z", tm);
    printf("%s\n", buf);
    return 0;
}

上面的代码片段在编译和运行时为我打印了 CEST

关于c - 在 C 编程中存储系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25522926/

相关文章:

参数数组大小表达式的 const

c - pthread 编程中的段错误

mysql - MySQL中两个日期之间的差异

ruby - 为什么 Ruby 的 DateTime.new_offset 不在 rdoc 中

c - APUE 10.3 信号 : pointer cast issue.

c - 主机和客户端无法在我的聊天程序中使用 select() 进行通信

c - C中的变量Arity?

java - 为什么我的 DateTime 反序列化会截断 DateTime 分钟/秒/毫秒?

python - Pandas 将基于日期时间类型的数据框分组到忽略日期部分的不同时期

python - 滚动平均数据绘图未正确平滑