#include <stdio.h>
#include <string.h>
#define PSDLEN 6
void inputPsd(char *str) /*處理輸入*/
{
int i;
for(i = 0; i < PSDLEN; i++)
{
while(1)
{
str[i] = getch();
if(str[i] == '\b') /*處理退格鍵*/
{
i--;
if(i < 0)
{
i = 0;
}
else
{
printf("\b \b");
}
continue;
}
else if(str[i] == '\r') /*處理回車鍵*/
{
continue;
}
else
{
printf("*");
break;
}
}
}
str[i] = '\0';
printf("\n");
}
int checkFirst() /*檢測是否是第壹次使用*/
{
FILE *fp;
if((fp = fopen("psd.dat", "rb")) == NULL)
{
return 1;
}
fclose(fp);
return 0;
}
void firstUse() /*第壹次使用 需要輸入密碼*/
{
FILE *fp;
int i;
char passwd[PSDLEN + 1];
char checkPsd[PSDLEN + 1];
if((fp = fopen("psd.dat", "wb")) == NULL)
{
printf("Creat password error!\n");
exit(1);
}
while(1)
{
printf("Please input password:");
inputPsd(passwd);
printf("\nPlease input password again:");
inputPsd(checkPsd);
if(!strcmp(passwd, checkPsd))
{
break;
}
printf("\ncheck password error! \n");
}
fwrite(passwd, sizeof(char), PSDLEN, fp);
fclose(fp);
}
void login() /*核對密碼,並登錄*/
{
FILE *fp;
int i, num = 3;
char passwd[PSDLEN + 1];
char checkPsd[PSDLEN + 1];
if((fp = fopen("psd.dat", "rb")) == NULL)
{
puts("Open psd.dat error");
exit(1);
}
fread(passwd, sizeof(char), PSDLEN, fp);
fclose(fp);
passwd[PSDLEN] = '\0';
printf("Please input password to login");
while(num)
{
printf("you have %d chances to cry:\n", num);
inputPsd(checkPsd);
if(!strcmp(passwd, checkPsd))
{
break;
}
puts("\npassword error,Please input again");
num--;
}
if(!num)
{
puts("Press any key to exit...");
getch();
exit(0);
}
else
{
puts("\n--------\nWelcome!\n--------\n");
}
}
void main()
{
if(checkFirst())
{
firstUse();
}
else
login();
getch();
}