我有一个 C 程序,它使用以下行将时间戳打印为字符串:
sprintf (scratch_buffer, "%s\0", dfr_time_date_strg);
此时间戳始终打印为 UTC,但我想添加调用字符串 date +%z
和 date +%Z
。
两个时区值可以这样调用:
system("date +%z");
system("date +%Z");
但是我如何将它们分配给名为 tz_offset
和 tz_name
的 char
字符串,以便最终的时间戳打印行是:
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/