场景:
1. Windows软件开发时总是需要格式化时间, 获取软件的copyright时间,获取临时目录, 获取下载目录和AppData目录, 这些方法部分如果不搜索的话MSDN真的很难找.
2. 可跨产品移植.
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#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 可能会出现崩溃的情况,数值太大或负数或0.
#define _MAX__TIME64_T 0x793406fffi64
static time_t FixupTime64Range(const time_t time)
{
time_t tmp_time = time;
if(tmp_time < 0 ||// underflow
tmp_time > (_MAX__TIME64_T - 14 * 60 * 60)) // 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];
DWORD dwRetVal = GetTempPath(MAX_PATH, // length of the buffer
lpTempPathBuffer); // buffer for path
std::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,
szPath)))
{
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,
szPath)))
{
std::wstring path(szPath);
path.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();
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/infoworld/article/details/49530723