Scene:
1. Windows software development always need to format time, get the software's copyright time, get temporary directory, get download directory and AppData directory, these methods parts if not search MSDN really hard to find.
2. Can be ported across products.
Bas_utility_sys.h:
#ifndef __bas_utility_sys_h#define__bas_utility_sys_h#include "Bas_exp.h" #include <Windows.h> #include < stdio.h> #include <time.h>class lib_basic basutilitysys{public://"%y-%m-%d%h:%m:%s" static void TimeFormat ( time_t ntime, char *szdst,const char* format), static void Getnowdatetime (char *szdst,const char* format), static wchar_t* Getcompileyear (); static wchar_t* Gettempdir (); static wchar_t* Getdownloaddir (); static wchar_t* Getappdatadir ();}; #endif
Bas_utility_sys.cpp:
#include "basic/bas_utility_sys.h" #include <Windows.h> #include <tchar.h> #include <shlobj.h># Include <time.h> #include <string.h> #include <string>//1.localtime may crash, values are too large or negative or 0. #define _ max__time64_t 0x793406fffi64static time_t fixuptime64range (const time_t time) {time_t tmp_time = time;if (Tmp_time < 0 | | Underflowtmp_time > (_MAX__TIME64_T-14 *)//overflow{tmp_time = 0;//reset time to 0}return tmp_time;} void Basutilitysys::timeformat (time_t ntime, char *szdst,const char* format) {struct TM m_tm;time_t TT = Fixuptime64range (ntime); M_tm = *localtime (&TT); strftime (SZDST,20,FORMAT,&M_TM);} void Basutilitysys::getnowdatetime (char *szdst,const char* format) {time_t t = time (NULL); TimeFormat (T,szdst,format);} wchar_t* basutilitysys::getcompileyear () {static const wchar_t* date = _t (__date__); const wchar_t* last = WCSRCHR (date,l ' '); std::wstring year (last+1); return Wcsdup (Year.c_str ());} wchar_t* Basutilitysys::gettempdir () {TCHAR Lptemppathbuffer[max_path];D Word dwretval = GetTempPath (MAX_PATH,//length of the buffer Lptemppathbuffer); Buffer for pathstd::wstring path (lptemppathbuffer); return Wcsdup (Path.c_str ());} wchar_t* Basutilitysys::getappdatadir () {wchar_t *szpath = (wchar_t*) malloc (sizeof (wchar_t) *max_path); Memset (szpath , 0,sizeof (wchar_t) *max_path); if (SUCCEEDED (SHGetFolderPath (NULL, csidl_appdata| Csidl_flag_create, NULL, 0, s Zpath)) {Szpath[wcslen (szpath)] = L ' \ \ '; return szpath;} Else{return Gettempdir ();}} wchar_t* Basutilitysys::getdownloaddir () {wchar_t Szpath[max_path]; if (SUCCEEDED (SHGetFolderPath (NULL, csidl_profile| Csidl_flag_create, NULL, 0, s Zpath)) {std::wstring path (szpath);p ath.append (L "\\Downloads"), if (_waccess (Path.c_str (), 0) = = 0) {path.append (L "\ \"); return Wcsdup (Path.c_str ());} Else{bool res = CreateDirectory (Path.c_str (), NULL), if (res) {path.append (L "\ \"), Return Wcsdup (Path.c_str ());} Else{return Gettempdir ();}} }return Gettempdir ();}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Software]_[windows]_[Utility System Tool class]