需求:
写一个usr.txt文档,文档中每一行的格式为:姓名 密码 例如:
zhangsan 123456
lisi abcdef
任务:
代码实现过程:
#include<stdio.h>
#include<string.h>
int main(int argc, const char *argv[])
{
FILE *fp=fopen("./usr.txt","a+");
if(NULL==fp){
printf("打开失败\n");
perror("fopen");
return -1;
}
char name[64];
char code[64];
printf("请输入您的账户:");
scanf("%s",name);
printf("请输入您的密码:");
scanf("%s",code);
char ifname[64];
char ifcode[64];
int res1=0;
int res2=0;
while(1){
res1 = fscanf(fp,"%s %s",ifname,ifcode);
if(strcmp(ifname,name)==0){
if(strcmp(ifcode,code)!=0){
printf("密码错误\n");
break;
}
else{
printf("登陆成功\n");
break;
}
}
else if(res1==EOF){
printf("账户不存在\n");
break;
}
}
if(fclose(fp)<0){
printf("关闭失败\n");
perror("fclose");
return -1;
}
代码实现结果:
ubuntu@ubuntu:day1$ gcc hw.c
ubuntu@ubuntu:day1$ ./a.out
请输入您的账户:zhangsan
请输入您的密码:123456
登陆成功
ubuntu@ubuntu:day1$ ./a.out
请输入您的账户:lisi
请输入您的密码:654321
登陆成功
ubuntu@ubuntu:day1$ ./a.out
请输入您的账户:lisi
请输入您的密码:15534
密码错误
ubuntu@ubuntu:day1$ ./a.out
请输入您的账户:fch
请输入您的密码:1435
账户不存在
ubuntu@ubuntu:day1$