2010-05-26 64 views
2

我可以使用struct tm和time(),localtime(),asctime()獲取系統時間,但是我需要關於如何使用c程序設置系統時間的幫助。使用c庫函數的系統時間設置

+0

什麼操作系統? – 2010-05-26 19:40:48

+0

linux操作系統。 – neo730 2010-05-27 05:24:18

回答

4

,如果你不希望執行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結構持有秒鐘,UTC 00:00:00(Unix紀元時間)1970年1月1日號(作爲long)加微秒數(作爲long)。所以你需要計算這些數字來設定時間。你可以使用這些helper functions,以更好地處理與timeval結構的處理。

+0

再次感謝盧克... 對不起,bcoz我忘了基本.....看看MAN頁面。 – neo730 2010-05-27 05:22:36

+0

經常這些天我只是使用谷歌搜索手冊頁(除非我在那裏在終端),通常「我感覺幸運」搜索指甲每次只要你輸入男人'查詢'。如果您使用的是Firefox或Chrome,則只需將其輸入到地址欄即可。 – luke 2010-05-27 16:31:44

+0

tv_usec實際上是微秒而不是毫秒 – Zaid 2017-11-03 14:18:27