当前位置:网站首页>工作中一些常用的工具函數
工作中一些常用的工具函數
2022-06-23 23:45:00 【無聊的阿樂】
來自於自己寫的加密機客戶端源碼,包括時間日期格式校驗,IP校驗,大小端轉換,文件查找等
#include"util.h"
#include<string>
#include"Language.h"
//按回車鍵退出
void GETCHAR()
{
cout<< Language::Instance()->GetContent(OutMessage::PressEnter) <<endl;
cin.ignore();//因為有回調函數返回,需要忽略掉緩沖區的內容
getchar();
}
//不用getch()實現密碼的輸入,回顯為*,最大可輸入16比特數, 使密碼以*號輸出
#define BACKSPACE 0x08 //删除鍵的asccll碼值
char* InputCode(char *pass)
{
int i = 0;
system("stty -icanon"); //設置一次性讀完操作,即getchar()不用回車也能獲取字符
system("stty -echo"); //關閉回顯,即輸入任何字符都不顯示
while(i < 16)
{
pass[i]=getchar(); //獲取鍵盤的值到數組中
if(i == 0 && pass[i] == BACKSPACE)
{
i=0; //若開始沒有值,輸入删除,則,不算值
pass[i]='\0';
continue;
}
else if(pass[i] == BACKSPACE)
{
printf("\b \b"); //若删除,則光標前移,輸空格覆蓋,再光標前移
pass[i]='\0';
i=i-1; //返回到前一個值繼續輸入
continue; //結束當前循環
}
else if(pass[i] == '\n') //若按回車則,輸入結束
{
pass[i]='\0';
break;
}
else
{
printf("*");
}
i++;
}
system("stty echo"); //開啟回顯
system("stty icanon"); //關閉一次性讀完操作,即getchar()必須回車也能獲取字符
cout<<endl;
return pass; //返回最後結果
}
//大端轉小端
UINT reversebytes_UINT(UINT value)
{
return (value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 |
(value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24;
}
//判斷輸入的ip和mask是否有效
bool IpValid(string str)
{
struct in_addr addr;
int ret;
ret = inet_pton(AF_INET, str.c_str(), &addr);
if( ret != 1 )
{
return false;
}
return true;
}
//時間轉換函數
long metis_strptime(char *str_time)
{
struct tm stm;
strptime(str_time, "%Y-%m-%d %H:%M:%S",&stm);
long t = mktime(&stm);//將時間轉換為自1970年1月1日以來逝去時間的秒數,發生錯誤時返回-1.
return t;
}
//日志級別轉換
string LogLevelConvert(BYTE level)
{
string strloglevel;
switch ((int)level)
{
case 0://
strloglevel = "Debug";
break;
case 1://
strloglevel = "Info";
break;
case 2://
strloglevel = "Warn";
break;
case 3://
strloglevel = "Error";
break;
case 4://
strloglevel = "Fatal";
break;
default:
cout << "LogLevel輸入有誤!" << endl;
break;
}
return strloglevel;
}
//查找更新文件
int FindUpGradeFile(char *filename)
{
DIR *dir;
struct dirent *ptr;
string path = "./upgrade";
char *dirpath = (char*)(path.c_str());
char *filenames = (char*)".xml";
char *curfilename = NULL;
int findflag = 0;
if ((dir = opendir(dirpath)) == NULL)
{
perror("Open dir error...");
return -1;
}
while ((ptr = readdir(dir)) != NULL)//讀取到目錄文件尾則返回NULL
{
curfilename = rindex(ptr->d_name, '.');
if (curfilename != NULL&& strcmp(curfilename, filenames) == 0)
{
//printf("find file name :%s\n", ptr->d_name); //ptr->d_name為找到的文件名
findflag = 1;
break;
}
}
if (0 == findflag)
{
cout<< Language::Instance()->GetContent(OutMessage::NoUpgradeFile) <<endl;
return -1;
}
else
{
strcpy(filename, ptr->d_name);
//printf("Find the upgrade file is: %s\n", filename);
cout<< Language::Instance()->GetContent(OutMessage::FindUpgradeFile) << ptr->d_name <<endl;
}
closedir(dir);
return 0;
}
/*時間格式判斷子函數*/
std::string trim(const std::string& str)
{
std::string::size_type pos = str.find_first_not_of(' ');
if (pos == std::string::npos) {
return str;
}
std::string::size_type pos2 = str.find_last_not_of(' ');
if (pos2 != std::string::npos) {
return str.substr(pos, pos2 - pos + 1);
}
return str.substr(pos);
}
void split(const std::string& str, std::vector<std::string>* ret_, std::string sep = ",")
{
if (str.empty()) {
return;
}
std::string tmp;
std::string::size_type pos_begin = str.find_first_not_of(sep);
std::string::size_type comma_pos = 0;
while (pos_begin != std::string::npos) {
comma_pos = str.find(sep, pos_begin);
if (comma_pos != std::string::npos) {
tmp = str.substr(pos_begin, comma_pos - pos_begin);
pos_begin = comma_pos + sep.length();
}
else {
tmp = str.substr(pos_begin);
pos_begin = comma_pos;
}
if (!tmp.empty()) {
ret_->push_back(tmp);
tmp.clear();
}
}
}
bool DateVerify(int year, int month, int day)
{
// 這裏限制了年份需要在1970-2100,可去掉
if (year < 1970 || year > 2100 || month < 1 || month > 12 || day < 1 || day > 31)
{
return false;
}
switch (month) {
case 4:
case 6:
case 9:
case 11:
if (day > 30) {
// 4.6.9.11月天數不能大於30
return false;
}
break;
case 2:
{
bool bLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if ((bLeapYear && day > 29) || (!bLeapYear && day > 28)) {
// 閏年2月不能大於29天;平年2月不能大於28天
return false;
}
}
break;
default:
break;
}
return true;
}
// 校驗yyyy/mm/dd
bool CheckDateValid(const std::string& strDate)
{
std::string strPureDate = trim(strDate);
if (strPureDate.length() < 8 || strPureDate.length() > 10) {
return false;
}
std::vector<std::string> vecFields;
split(strPureDate, &vecFields, "-");
if (vecFields.size() != 3) {
return false;
}
// TODO:這裏最好再下判斷字符轉換是否成功
int nYear = atoi(vecFields[0].c_str());
int nMonth = atoi(vecFields[1].c_str());
int nDay = atoi(vecFields[2].c_str());
return DateVerify(nYear, nMonth, nDay);
}
// 校驗HH:MM:SS
bool CheckTimeValid(const std::string& strTime)
{
std::string strPureTime = trim(strTime);
if (strPureTime.length() < 5 || strPureTime.length() > 8) {
return false;
}
std::vector<std::string> vecFields;
split(strPureTime, &vecFields, ":");
if (vecFields.size() != 3) {
return false;
}
int nHour = atoi(vecFields[0].c_str());
int nMinute = atoi(vecFields[1].c_str());
int nSecond = atoi(vecFields[2].c_str());
bool bValid = (nHour >= 0 && nHour <= 23);
bValid = bValid && (nMinute >= 0 && nMinute <= 59);
bValid = bValid && (nSecond >= 0 && nSecond <= 59);
return bValid;
}
// 日期格式為: yyyy/mm/dd || yyyy/mm/dd HH:MM:SS yyyy-mm-dd HH:MM:SS
bool CheckDateTimeValid(const std::string& strDateTime)
{
std::string strPureDateTime = trim(strDateTime);
std::vector<std::string> vecFields;
split(strPureDateTime, &vecFields, " ");
if (vecFields.size() != 1 && vecFields.size() != 2) {
return false;
}
// 僅有日期
if (vecFields.size() == 1) {
return CheckDateValid(vecFields[0]);
}
return CheckDateValid(vecFields[0]) && CheckTimeValid(vecFields[1]);
}
边栏推荐
- STM32-------外部中断
- 日化用品行业集团采购管理系统改变传统采购模式,降低采购成本
- How can wechat video numbers be broadcast live on a PC?
- 2022 information security engineer examination knowledge point: access control
- 2022年信息安全工程师考试知识点:访问控制
- 嵌入式接口之TIM定时器与NVIC的STM32模板库函数的一些解释
- Graph theory (nearest common ancestor LCA)
- Which securities dealers recommend? Is online account opening safe?
- 项目中常用到的 19 条 MySQL 优化
- Grpc security -2: fast implementation of server-side JWT authentication
猜你喜欢

ORB_SLAM3环境搭建及demo演示

VS QT VTK 左下角显示同步小坐标轴

"Shanda Diwei Cup" the 12th Shandong ICPC undergraduate program design competition

HDLBits-&gt; Circuits-&gt; Arithmetic Circuitd-&gt; 3-bit binary adder

Embedded interface review materials

Niuke.com: the double pointer problem of receiving rainwater

这个高仿小米商城项目太惊艳了

Telecommuting: how to become a master of time management| Community essay solicitation

多门店药品进销存系统源码 大型连锁药店管理系统源码

High imitation Book flag novel flutter edition, learn it
随机推荐
Acrel-3000WEB电能管理系统在都巴高速的应用
生成式对抗网络(GANs)及变体
STM32-------定时器
E: Unable to acquire lock /var/lib/dpkg/lock
一个人竟然撸了一个微博 APP
PyQt5_QTableWidget分页单选右键菜单控件
三款很酷很骚气的底部导航
Math. Max() method obtains the maximum value in the array and returns Nan problem analysis
What is an applet container
日化用品行业集团采购管理系统改变传统采购模式,降低采购成本
【Try to Hack】masscan
2022年信息安全工程師考試知識點:訪問控制
Graph theory (tree diameter)
数字物业管理成趋势,传统物业公司如何通过转型实现数字化蝶变?
Why can't the netherworld fortress machine be remotely connected to the server? What are the ways to solve such problems?
Bitmap load memory analysis
Several guesses about the design of Tencent conference number
嵌入式接口之TIM定时器与NVIC的STM32模板库函数的一些解释
Which securities dealers recommend? Is online account opening safe?
What is the production process of enterprise website? How long does it take to design and build a website?