20.2.5 Example: Setting the System Time

The following code allows the user to set the system time:

static char *aszDay[] = { "Sunday", "Monday", "Tuesday", "Wednesday",

"Thursday", "Friday", "Saturday" };

void _cdecl main(void)

{

HANDLE hToken;

SYSTEMTIME st;

char szTime[25], *pc;

TOKEN_PRIVILEGES tkp;

GetSystemTime(&st); /* get current time; cannot fail */

ShowTime(&st); /* display the current time */

for (;;) { /* get the new time in hh:mm format */

printf("enter new time: ");

gets(szTime);

if ((pc = strchr(szTime, ':')) != NULL) {

*pc = '\0';

st.wHour = (WORD)atoi(szTime);

st.wMinute = (WORD)atoi(pc + 1);

break;

}

else {

puts("time must be in hh:mm format");

}

}

/* get current process token handle */

/* so we can get set time privilege */

if (!OpenProcessToken(GetCurrentProcess(),

TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))

error("OpenProcessToken");

/* get the LUID for system time privilege */

LookupPrivilegeValue(NULL, "SeSystemtimePrivilege",

&tkp.Privileges[0].Luid);

tkp.PrivilegeCount = 1; /* one privilege to set */

tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

/* get set-time privilege for this process */

if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,

(PTOKEN_PRIVILEGES)NULL, 0))

error("AdjustTokenPrivileges enable");

if (!SetSystemTime(&st)) /* set the system time */

error("SetSystemTime");

ShowTime(&st);

/* now disable set-time privilege */

tkp.Privileges[0].Attributes = 0;

if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,

(PTOKEN_PRIVILEGES)NULL, 0))

error("AdjustTokenPrivileges disable");

}

void error(LPSTR lpszFunction)

{

DWORD dw = GetLastError();

printf("%s failed: GetLastError returned %u\n", lpszFunction, dw);

ExitProcess(dw);

}

void ShowTime(PSYSTEMTIME pst)

{

printf("It is now %02u:%02u:%02u on %s, %02u/%02u/%4u\n",

pst->wHour, pst->wMinute, pst->wSecond, aszDay[pst->wDayOfWeek],

pst->wMonth, pst->wDay, pst->wYear);

}