3 Apr 2020

C++ Tips: Grab Current Username and Datetime using C++

收藏到CSDN网摘
From time to time, the current username and datetime need to be obtained in code for either saving system logs or debugging the code. If you are working in Windows like me, there are two functions available to do this. The first is GetUserName() in WinBase.h and the other is localtime() (and strftime() for formatting) in time.h (or  ). All you need to do is to include them in your header and call those functions when needed.

Here we go!



The following code sections will retrieve the username and formatted time string into two char arrays.
// get username
char userName[MAX_PATH];
DWORD size = MAX_PATH;
GetUserName(userName,&size);

// formatted time string
time_t t = time(0);
char timeStr[MAX_PATH];
strftime(timeStr,sizeof(timeStr),"%d/%m/%Y %H:%M:%S (%Z)",localtime(&t));

No comments :

Post a Comment