C++ struct tm example
C++에서 struct tm (시간 구조체) 사용 예
아래의 코드는 특정한 의미가 있는 것이 아니라 몇가지 함수사용 연습에 목적을 두고 있습니다.
특히 시리얼번호를 생성하는 알고리즘은 절대 아니므로 오해로 인한 시간을 허비하는 일이 없기를 바랍니다 ^^
사용된 함수들: time(), localtime_s(), mktime(), strcpy_s(), _countof(), _itoa(), atoi(), strcat_s(), sprintf_s(), strlen()
사용된 매크로 함수: A2W()
사용된 구조체: struct tm
#include <windows.h>
#include <tchar.h>
#include <iostream>
#include <atlconv.h>
#include <time.h>
using namespace std;
void getSerial(char* userName, char* sn);
int _tmain(int argc, _TCHAR* argv[])
{
int bPass = CheckSerial("홍길동","2554499258221");
cout << sn << endl; // 각 문자의 유니코드 숫자가 모두 연결된 문자열을 출력한다
cout << "인증결과=" << bPass << endl;
return 0;
}
/* 이용자 이름의 첫 두자를 이용하여 시리얼번호를 생성하고 두번째 파라미터로 전달되는 이용자 입력과 비교하여 인증한다*/
int CheckSerial(char* userName, char* userInput )
{
time_t tmsec;
time(&tmsec);
//cout << "time="<< tmsec << endl;
struct tm tmst;
localtime_s(&tmst, &tmsec);
int year = tmst.tm_year+1900;
int mon = tmst.tm_mon;
int mday = tmst.tm_mday;
int wday = tmst.tm_wday;
int hour = tmst.tm_hour;
int min = tmst.tm_min;
min = (min<30) ? 0 : 30;
tmst.tm_min = min;
tmst.tm_sec = 0;
tmsec = mktime(&tmst); // 30분 단위로 변경되는 초수
char month[12] = {'J','F','M','A','Y','J','U','G','S','O','N','D'};
char wday_arr[7] = {'S','M','T','W','H','F','A'};
USES_CONVERSION;
char *szMult = userName; // MBCS 문자열
wchar_t *wch = A2W(szMult); // 유니코드문자열로 변환
time_t n = (time_t)(wch[0]); // 유니코드 한 문자를 정수로 변환
n = (n<10000) ? n*year*1024 : n;
char ch1[64];// = "56412588";
sprintf_s(ch1, 16, "%d", n);
n = (time_t)(wch[1]);
n = (n<(time_t)10000)? n*(time_t)year : tmsec-((time_t)(n*year*5));
char ch2[64];
sprintf_s(ch2, 16, "%d", n);
char ch3[64]; // 년월일시분을 저장할 배열
sprintf_s(ch3, 16, "%d%d%d%d%d", year,mon+1,mday,hour, min);
time_t sec3 = (time_t)(atol(ch3)) - tmsec;
sprintf_s(ch3, 64, "%d", sec3);
char sn[64]; // 생성된 시리얼번호를 저장할 변수
sprintf_s(sn, 64, "%s%C%s%C%s", ch1,month[mon],ch2, wday_arr[wday], ch3);
cout << "DLL에서 생성한 시리얼=" << sn << ", 전달된 시리얼=" << userInput << endl;
if(strcmp(sn, userInput)==0)
{
cout << "인증성공" << endl;
return true;
}else{
cout << "인증실패" << endl;
return false;
}
}