gpt4 book ai didi

c - 使用c库函数设置系统时间

转载 作者:行者123 更新时间:2023-12-04 00:48:31 26 4
gpt4 key购买 nike

我可以使用 struct tm 和 time(),localtime(),asctime() 获取系统时间。但是我需要有关如何使用 c 程序设置系统时间的帮助。

最佳答案

如果您不想执行 shell 命令,您可以(如您所述)使用 settimeofday,我将从阅读 MAN page 开始,或寻找一些例子

这是一个例子:

#include <sys/time.h>
#include <stdio.h>
#include <errno.h>

int main(int argc, char *argv[])
{
struct timeval now;
int rc;

now.tv_sec=866208142;
now.tv_usec=290944;

rc=settimeofday(&now, NULL);
if(rc==0) {
printf("settimeofday() successful.\n");
}
else {
printf("settimeofday() failed, "
"errno = %d\n",errno);
return -1;
}

return 0;
}

无耻地从 IBMs documentation , struct timeval 结构保存从 1970 年 1 月 1 日开始的秒数(作为 long)加上微秒数(作为 long) , 00:00:00 UTC(Unix 纪元时间)。因此,您需要计算这些数字才能设置时间。您可以使用这些 helper functions , 以更好地处理 timeval 结构。

关于c - 使用c库函数设置系统时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2916170/

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