程序代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"choice.h"
void build_new()
{
mima *passbook1;
passbook1=(mima*)malloc(sizeof(mima));
size_t length1,length2;
FILE *fp_1;
printf("请输入新的用户名和密码\n");
printf("用户名:");
gets(passbook1->user_name);
printf("密码:");
gets(passbook1->password);
fp_1=fopen("load_pass.txt","wb");
length1=strlen(passbook1->user_name);
length2=strlen(passbook1->password);
if(fwrite(&length1,sizeof(size_t),1,fp_1)!=1)
printf("写入文件错误!\n");
else
{
printf("写入文件成功1!\n");
printf("length1=%d\n",length1);
fwrite(passbook1->user_name,sizeof(char),length1,fp_1);
}
if(fwrite(&length2,sizeof(size_t),1,fp_1)!=1)
printf("写入文件错误!\n");
else
{
printf("写入文件成功2!\n");
printf("length2=%d\n",length2);
fwrite(passbook1->password,sizeof(char),length2,fp_1);
}
fclose(fp_1);
load_user();
}
int load_user()
{
mima *passbook1,*passbook2;
passbook2=(mima*)malloc(sizeof(mima));
passbook1=(mima*)malloc(sizeof(mima));
size_t length1,length2;
FILE *fp_2;
printf("请输入用户名和密码\n");
printf("用户名:");
gets(passbook1->user_name);
printf("密码:");
gets(passbook1->password);
if((fp_2=fopen("load_pass.txt","rb"))!=NULL)
{
if(fread(&length1,sizeof(size_t),1,fp_2)!=1)
printf("读入文件错误!\n");
else
{
fread(passbook2->user_name,sizeof(char),length1,fp_2);
passbook2->user_name[length1]='\0';
printf("已经得到用户名\n");
/*for(int i=0;i<length2;i++)
printf("%c",passbook2->user_name[i]);
printf("\n");*/
fflush(stdout);
}
if(fread(&length2,sizeof(size_t),1,fp_2)!=1)
printf("读入文件错误!\n");
else
{
fread(passbook2->password,sizeof(char),length2,fp_2);
passbook2->password[length2]='\0';
printf("已经得到密码:");
/*for(int i=0;i<length2;i++)
printf("%c",passbook2->password[i]);
printf("\n");*/
fflush(stdout);
}
}
if(!strcmp(passbook2->user_name,passbook1->user_name)&&!strcmp(passbook2->password,passbook1->password))
{
free(passbook2);
free(passbook1);
printf("恭喜你登录成功!\n");
fclose(fp_2);
return 1;
}
else
{
free(passbook2);
free(passbook1);
printf("非常抱歉,失败了!\n");
fclose(fp_2);
return 0;
}
}
程序代码:
#include<stdio.h>
#include<string.h>
#include"choice.h"
int main()
{ char c;
printf("你是新用户?Y or N\n");
scanf("%c",&c);
getchar();
while(1)
{
switch(c)
{
case 'y':
case 'Y':build_new();return 0;
case 'n':
case 'N':load_user();break;
default:printf("错误,请重新输入!\n");
continue;
}
}
}
自己写的,貌似还不是很完美