當前位置:網站首頁>工作中一些常用的工具函數

工作中一些常用的工具函數

2022-06-23 23:45:10無聊的阿樂

來自於自己寫的加密機客戶端源碼,包括時間日期格式校驗,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]);
}


版權聲明
本文為[無聊的阿樂]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/174/202206232101472843.html

隨機推薦