当前位置:网站首页>工作中一些常用的工具函数
工作中一些常用的工具函数
2022-06-23 22:16: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]);
}
边栏推荐
- 为实现“双碳”目标,应如何实现节能、合理的照明管控
- 不同物体使用同一材质,有不同的表现
- Solve the problem that slf4j logs are not printed
- Niuke.com: the double pointer problem of receiving rainwater
- 2022 point de connaissance de l'examen des ingénieurs en sécurité de l'information: contrôle d'accès
- CVPR2019/图像翻译:TransGaGa: Geometry-Aware Unsupervised Image-to-Image Translation几何感知的无监督图像到图像的翻译
- Short video enters the hinterland of online music
- Fabric. JS manual bold text iText
- [Xilinx ax7103 microbalze Learning Notes 6] MicroBlaze custom IP core packaging experiment
- ACM. Hj89 24 point operation ●●●
猜你喜欢

项目中常用到的 19 条 MySQL 优化

What is the production process of enterprise website? How long does it take to design and build a website?

Golang 类型断言

PyQt5_QTableWidget分页单选右键菜单控件

Short video enters the hinterland of online music
![入参参数为Object,但传递过去却成了[object object] 是因为需要转为JSON格式](/img/8c/b1535e03900d71b075f73f80030064.png)
入参参数为Object,但传递过去却成了[object object] 是因为需要转为JSON格式

Analysis on the advantages and disadvantages of the best 12 project management systems at home and abroad

微信录制视频转圈效果如何实现?

如何保证高速公路供电可靠

STM32------ADC(电压检测)
随机推荐
2022 Shandong Health Expo, Jinan International Health Industry Expo, China Nutrition and Health Exhibition
Telecommuting: how to become a master of time management| Community essay solicitation
Onsaveinstancestate callback opportunity of activity
[Xilinx ax7103 microbalze Learning Notes 6] MicroBlaze custom IP core packaging experiment
Postman返回值中文乱码????
What to check for AIX system monthly maintenance (II)
What is an applet container
在OpenCloudOS使用snap安装.NET 6
List中subList的add造成的死循环
Activity的onSaveInstanceState回调时机
Sorry, your USB cable may be wrong!
The digital transformation index report 2021 released by Tencent Research Institute has accelerated the digital transformation and upgrading of mainland enterprises!
Bitmap加载内存分析
Stm32----- timer
Thinking (87): Protocol encryption and compression
PLC数据操作系列之构造不同应用场景的缓存栈FIFO(算法详解)
ACM. Hj89 24 point operation ●●●
腾讯会议号设计的几种猜测
laravel之任务队列
ARouter 组件之间跳转需免混淆