Another setlocale(), _gmtime64_s(), _time64() and strftime() C function examples
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Target platform: none, just for learning
Header file: Standard and Windows
Additional library: Windows Platform SDK
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info: non-CLR or unmanaged
To do: Usage of setlocale() when using two independent threads
To show: Using the setlocale(), _gmtime64_s(), _time64() and strftime() C function examples
// setlocale(): This program demonstrates the use of setlocale() when using two independent threads.
#include <locale.h>
#include <process.h>
#include <windows.h>
#include <stdio.h>
#include <time.h>
#define BUFF_SIZE 100
// Retrieve the date and time in the current locale's format.
int get_time(unsigned char* str)
{
__time64_t ltime;
struct tm thetime;
// Retrieve the time
_time64(<ime);
_gmtime64_s(&thetime, <ime);
// Format the current time structure into a string using %#x is the long date representation, appropriate to the current locale
if (!strftime((char *)str, BUFF_SIZE, "%#x", (const struct tm *)&thetime))
{
printf("strftime failed!\n");
return 1;
}
return 0;
}
// This thread sets its locale to German and prints the time.
unsigned __stdcall SecondThreadFunc(void* pArguments)
{
unsigned char str[BUFF_SIZE];
// Set the thread local
printf("The thread locale is now set to %s.\n", setlocale(LC_ALL, "Dutch"));
// Retrieve the time string from the helper function
if (get_time(str) == 0)
{
printf("The time in Dutch locale is: '%s'\n", str);
}
_endthreadex(0);
return 0;
}
// The main thread spawns a second thread (above) and then sets the locale to English and prints the time.
int main(void)
{
HANDLE hThread;
unsigned threadID;
unsigned char str[BUFF_SIZE];
// Configure per-thread locale to cause all subsequently created threads to have their own locale.
_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
// Retrieve the time string from the helper function
printf("The thread locale is now set to %s.\n", setlocale(LC_ALL, "English"));
// Create the second thread.
hThread = (HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, NULL, 0, &threadID);
if (get_time(str) == 0)
{
// Retrieve the time string from the helper function
printf("The time in English locale is: '%s'\n\n", str);
}
// Wait for the created thread to finish.
WaitForSingleObject(hThread, INFINITE);
// Destroy the thread object.
CloseHandle( hThread );
}
Output example:
The thread locale is now set to English_United States.1252.
The time in English locale is: 'Sunday, December 17, 2006'
The thread locale is now set to Dutch_Netherlands.1252.
The time in Dutch locale is: 'zondag 17 december 2006'
Press any key to continue . . .