#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>int IsDigitBuf(char *sBuf, int nLen)
{
int i; if (nLen == 0) return 1;
if (nLen > strlen(sBuf)) nLen = strlen(sBuf); for (i = 0; i < nLen; i++)
if (!isdigit(sBuf[i])) return 0; return 1;
}int checkdate(int iYear, int iMonth, int iDay)
{
if (iYear < 0 || iYear > 9999)
return -1;
switch (iMonth)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (iDay <= 0 || iDay > 31)
{
return -3;
}
break;
case 4:
case 6:
case 9:
case 11:
if (iDay <= 0 || iDay > 30)
{
return -3;
}
break;
case 2:
if ((iYear % 4 == 0 && iYear % 100 != 0) || iYear % 400 == 0)
{
if (iDay <= 0 || iDay > 29)
{
return -3;
}
}
else
{
if (iDay <= 0 || iDay > 28)
{
return -3;
}
}
break;
default:
return -2;
}
return 0;
}int CheckStrDate(char *sDate)
{
int iRet; char sYear[5];
char sMonth[3];
char sDay[3]; memset(sYear, 0, sizeof(sYear));
memset(sMonth, 0, sizeof(sMonth));
memset(sDay, 0, sizeof(sDay)); if (strlen(sDate) != 8)
{
return -1;
} memcpy(sYear, sDate, 4);
memcpy(sMonth, sDate+4, 2);
memcpy(sDay, sDate+6, 2); iRet = checkdate(atoi(sYear), atoi(sMonth), atoi(sDay));
if (iRet != 0)
{
return -1;
} return 0;
}int main(int argc, char *argv[])
{
int i;
int iRet;
int iWeight[18] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1};
char cCheck[11] = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
char sIdCardNo[20];
char sDate[8 + 1];
int iDate;
int Sum = 0; if (argc < 2) {
printf("FAIL\n");
exit(1);
} memset(sIdCardNo, 0, 20);
memcpy(sIdCardNo, argv[1], 18);
if ((strlen(sIdCardNo) == 15) && ((iRet = IsDigitBuf(sIdCardNo, 15)) > 0)) {
printf("OK\n");
exit(0);
} else if (strlen(sIdCardNo) != 18) {
printf("FAIL\n");
exit(1);
} /* 身份证7-14位是否有效 */
memset(sDate, 0, sizeof(sDate));
memcpy(sDate, sIdCardNo + 6, 4);
iDate = atoi(sDate);
if (iDate < 1900 || iDate > 2020) {
printf("FAIL\n");
exit(1);
}
memset(sDate, 0, sizeof(sDate));
memcpy(sDate, sIdCardNo + 6, 8);
iRet = CheckStrDate(sDate);
if (iRet < 0) {
printf("FAIL\n");
exit(1);
} /* 身份证18位校验位是否有效 */
for (i = 0; i < 17; i ++) {
memset(sDate, 0, sizeof(sDate));
sDate[0] = sIdCardNo[i];
iDate = atoi(sDate);
Sum += iWeight[i] * iDate;
}
Sum %= 11;
if ('x' == sIdCardNo[17]) {
sIdCardNo[17] = 'X';
}
if (cCheck[Sum] != sIdCardNo[17]) {
printf("FAIL\n");
exit(1);
} printf("OK\n");
exit(0);
}