//系统授权时间校验
time_t tmpTime = time(NULL);
if (tmpTime > (1615948779 + 3600)){
MessageBox(L"授权到期,请联系开发者!");
exit(0);
}
1. 获得当前系统启动以来的时间
#include <time.h>
unsigned long GetTickCount()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts); //CLOCK_MONOTONIC 不会受系统时间改变影响
return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
}
如果编译不过加 -lrt
2. 获得系统时间,精确到毫秒级(查了半天资料,windows的孩子转Linux伤不起啊,后来测试发现gettimeofday是有“时间倒流” 现象的,晕死)
void GetLoclTime(char * szTimeBuf)
{
struct timeval tv;
struct tm *tm;
gettimeofday(&tv, NULL);
tm = localtime(&tv.tv_sec);
sprintf(szTimeBuf, "%04d-%02d-%02d %02d:%02d:%02d:%03d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min,
tm->tm_sec, tv.tv_usec/1000);
}
3.printf()中的占位符
%llu unsinged long long
%lld long long
%lu unsinged long
%ld long
4.判断一个数是否是偶数
利用2进制进行判断,奇数的最低位一定是1,而偶数的最低位一定是0.所以我们可以根据这个特性,让需要判定的整数和1进行“与”运算,这样就只留下了原数的最低位,然后直接判断这个数等于1还是等于0即可
if
( (num & 0x1) == 0 )
{
puts
(
"偶数"
);
}
else
{
puts
(
"奇数"
);
}
5.从CString得到字符数组,避免每次都要ReleaseBuffer()
bool GetTextFromCString(CString srcStr, char *pszDesBuf, int iDesBufLen)
{
int iSrcStrLen = srcStr.GetLength();
if (iSrcStrLen > (iDesBufLen - 1))
{
MessageBox(NULL, "Des buf is short then CString len!", "Error", MB_OK);
return false;
}
memset(pszDesBuf, '\0', iDesBufLen);
memcpy(pszDesBuf, srcStr.GetBuffer(), iSrcStrLen);
srcStr.ReleaseBuffer();
return true;
}
6. 精确到毫秒级时间统计
class CTimeCount
{
public:
CTimeCount()
{
QueryPerformanceFrequency((LARGE_INTEGER*)&m_dwFrequency);
QueryPerformanceCounter((LARGE_INTEGER*)&m_dwStartTime);//开始时间
}
float Span()
{
QueryPerformanceCounter((LARGE_INTEGER*)&m_dwCurTime);//结束时间
double dwSpan = (double)(m_dwCurTime - m_dwStartTime) / (double)m_dwFrequency;
float fSpan = dwSpan * 1000;
return fSpan;
}
void ReSet()
{
QueryPerformanceCounter((LARGE_INTEGER*)&m_dwStartTime);//开始时间
}
private:
__int64 m_dwFrequency;
__int64 m_dwStartTime;
__int64 m_dwCurTime;
};
7. 判断是否为汉字
在ANSI C标准中一个汉字由两个字节组成,判断一个字符是否为汉字就是判断第一个字节的最高位是否为1。可以通过char a[i]&0x80来进行比较
int level = 3;
char* str = "小鱼85";
const char *tmp = str;
while(level-- && *tmp ){
if((*tmp) & 0x80 )
{
tmp++;
}
tmp++;
}
8.按行读取文件(中间有空行也是支持的)
void ReadData()
{
ifstream fin("C:\\windows\\system.ini");
string s;
int i = 0;
while( getline(fin,s) )
{
i++;
char szBuf[8] = {'\0'};
sprintf(szBuf, "%d:", i);
cout << szBuf << s << endl;
}
}
9.判断字符串是否整数
bool BeInt(string s)
{
stringstream sin(s);
int t;
char p;
if(!(sin >> t))
return false;
if(sin >> p)
return false;
else
return true;
}
10.用16进制打印内存
string GetBufHex(const char* buf, size_t len)
{
string strHex = "";
//printf("The Hex output of data :/n/t0x");
for(size_t i=0; i<len; ++i)
{
char szBuf[4] = {'\0'};
unsigned char c = buf[i]; // must use unsigned char to print >128 value
if( c< 16)
{
sprintf(szBuf, " 0%x",c);
//printf("0%x", c);
}
else
{
sprintf(szBuf, " %x", c);
//printf("%x", c);
}
string strData = szBuf;
strHex += strData;
}
return strHex;
//printf("/n");
}
urlencode
unsigned char ToHex(unsigned char x)
{
return x > 9 ? x + 55 : x + 48;
}
unsigned char FromHex(unsigned char x)
{
unsigned char y;
if (x >= 'A' && x <= 'Z') y = x - 'A' + 10;
else if (x >= 'a' && x <= 'z') y = x - 'a' + 10;
else if (x >= '0' && x <= '9') y = x - '0';
else assert(0);
return y;
}
std::string UrlEncode(const std::string& str)
{
std::string strTemp = "";
size_t length = str.length();
for (size_t i = 0; i < length; i++)
{
if (isalnum((unsigned char)str[i]) ||
(str[i] == '-') ||
(str[i] == '_') ||
(str[i] == '.') ||
(str[i] == '~'))
strTemp += str[i];
else if (str[i] == ' ')
strTemp += "+";
else
{
strTemp += '%';
strTemp += ToHex((unsigned char)str[i] >> 4);
strTemp += ToHex((unsigned char)str[i] % 16);
}
}
return strTemp;
}
std::string UrlDecode(const std::string& str)
{
std::string strTemp = "";
size_t length = str.length();
for (size_t i = 0; i < length; i++)
{
if (str[i] == '+') strTemp += ' ';
else if (str[i] == '%')
{
assert(i + 2 < length);
unsigned char high = FromHex((unsigned char)str[++i]);
unsigned char low = FromHex((unsigned char)str[++i]);
strTemp += high*16 + low;
}
else strTemp += str[i];
}
return strTemp;
}
int main()
{
string strUrl = UrlEncode("http://baidu.com/users/xiao+?/@小雨");
cout << strUrl << endl;
char ch;
cin >> ch;
}
base64 编解码
//因为有换行符,所以编码之后,js无法正常解析,要去掉换行符
string Base64Encode(const char* Data,int DataByte)
{
//编码表
const char EncodeTable[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//返回值
string strEncode;
unsigned char Tmp[4]={0};
int LineLength=0;
for(int i=0;i<(int)(DataByte / 3);i++)
{
Tmp[1] = *Data++;
Tmp[2] = *Data++;
Tmp[3] = *Data++;
strEncode+= EncodeTable[Tmp[1] >> 2];
strEncode+= EncodeTable[((Tmp[1] << 4) | (Tmp[2] >> 4)) & 0x3F];
strEncode+= EncodeTable[((Tmp[2] << 2) | (Tmp[3] >> 6)) & 0x3F];
strEncode+= EncodeTable[Tmp[3] & 0x3F];
if(LineLength+=4,LineLength==76)
{
strEncode+="\r\n";
LineLength=0;
}
}
//对剩余数据进行编码
int Mod=DataByte % 3;
if(Mod==1)
{
Tmp[1] = *Data++;
strEncode+= EncodeTable[(Tmp[1] & 0xFC) >> 2];
strEncode+= EncodeTable[((Tmp[1] & 0x03) << 4)];
strEncode+= "==";
}
else if(Mod==2)
{
Tmp[1] = *Data++;
Tmp[2] = *Data++;
strEncode+= EncodeTable[(Tmp[1] & 0xFC) >> 2];
strEncode+= EncodeTable[((Tmp[1] & 0x03) << 4) | ((Tmp[2] & 0xF0) >> 4)];
strEncode+= EncodeTable[((Tmp[2] & 0x0F) << 2)];
strEncode+= "=";
}
return strEncode;
}
string Base64Decode(const char* Data,int DataByte,int& OutByte)
{
OutByte = 0;
//解码表
const char DecodeTable[] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
62, // '+'
0, 0, 0,
63, // '/'
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9'
0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z'
0, 0, 0, 0, 0, 0,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z'
};
//返回值
string strDecode;
unsigned int nValue;
unsigned int i= 0;
unsigned char Tmp;
while (i < DataByte)
{
if (*Data != '\r' && *Data!='\n')
{
nValue = DecodeTable[*Data++] << 18;
nValue += DecodeTable[*Data++] << 12;
Tmp=(((nValue & 0x00FF0000) >> 16) + 256)%256 ;
strDecode+= Tmp;
OutByte++;
if (*Data != '=')
{
nValue += DecodeTable[*Data++] << 6;
Tmp=(((nValue & 0x0000FF00) >> 8) + 256)%256 ;
strDecode+= Tmp;
OutByte++;
if (*Data != '=')
{
nValue += DecodeTable[*Data++];
Tmp=((nValue & 0x000000FF) + 256)%256 ;
strDecode+= Tmp;
OutByte++;
}
}
i += 4;
}
else// 回车换行,跳过
{
Data++;
i++;
}
}
return strDecode;
}
void convert(unsigned char c, char* out) {
for (int i = 0; i<8; i++) {
*(out + i) = (c & (0x80 >> i)) == 0 ? 0x30 : 0x31;
}
}
char ch = '1';
char szValue[9] = { '\0' };
convert(ch, szValue);
遍历文件夹下的所有文件
void GetFiles( string path, vector<string>& files )
{
//文件句柄
long hFile ;
//文件信息
struct _finddata_t fileinfo;
string p;
if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) != 0)
{
do
{
//如果是目录,迭代之
//如果不是,加入列表
if((fileinfo.attrib & _A_SUBDIR))
{
if(strcmp(fileinfo.name,".") != 0 && strcmp(fileinfo.name,"..") != 0)
getFiles( p.assign(path).append("\\").append(fileinfo.name), files );
}
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
//if (fileinfo.name == "小鱼.txt")
{
cout << p << "\\" << fileinfo.name << endl;
}
}
}while(_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
std::string wstring2string(std::wstring wstr)
{
std::string result;
//获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的
int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
char* buffer = new char[len + 1];
//宽字节编码转换成多字节编码
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
buffer[len] = '\0';
//删除缓冲区并返回值
result.append(buffer);
delete[] buffer;
return result;
}
std::wstring string2wstring(std::string str)
{
std::wstring result;
//获取缓冲区大小,并申请空间,缓冲区大小按字符计算
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
TCHAR* buffer = new TCHAR[len + 1];
//多字节编码转换成宽字节编码
MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
buffer[len] = '\0'; //添加字符串结尾
//删除缓冲区并返回值
result.append(buffer);
delete[] buffer;
return result;
}
获取当前exe文件所在路径
string GetExePath()
{
TCHAR szPath[MAX_PATH];
if (!GetModuleFileName(NULL, szPath, MAX_PATH))
{
printf("GetModuleFileName failed (%d)\n", GetLastError());
return FALSE;
}
wstring wstrExePath(szPath);
int iPos = wstrExePath.find_last_of('\\');
wstrExePath = wstrExePath.substr(0, iPos);
string strExePath = wstring2string(wstrExePath);
return strExePath;
}