做这个简单的程序。这只是银行服务计划的第五部分。不知怎的,我被这个fread()
困住了。我无法比较用户和我的数据库的输入。当我的程序启动时,在我输入用户并传递它有点“挂起”或“冻结”之后会出现一个弹出窗口并显示“结束程序”。顺便说一下,我正在使用Dev C ++。
#include<stdio.h>
#include<string.h>
struct client
{
char accnum[9];
char accode[5];
char fname[20];
char lname[20];
}s;
main()
{
FILE *fp;
char user[9];
char pass[5];
fp=fopen("account.txt","a");
if(fp!=NULL)
{
/**
strcpy(s.accnum,"abcd1234");
strcpy(s.accode,"1234");
strcpy(s.fname,"john");
strcpy(s.lname,"doe");
fwrite(&s,sizeof(s),1,fp);
**/
printf("BANKING SERVICE");
printf("\nInput User: ");
gets(user);
printf("\nInput Pass: ");
gets(pass);
while(!feof(fp))
{
while(fread(&s,sizeof(s),1,fp)==1);
{
if(ferror(fp))
{
printf("error");
}
if (strcmp(user,s.accnum) == 0 && strcmp(pass,s.accode) == 0)
{
printf("\n\nsuccess!");
}
else
{
printf("\n\nerror!");
}
}
}
fclose(fp);
}
fclose(fp);
getch();
}
答案 0 :(得分:1)
在循环检查中是否成功匹配。如果未找到匹配项,则found
标记仍为零。然后在while循环完成后报告问题
fgets将包含换行符,因此在与文件内容进行比较之前必须将其删除,因为注释部分不显示任何换行符。
#include<stdio.h>
#include<string.h>
struct client
{
char accnum[9];
char accode[5];
char fname[20];
char lname[20];
}s;
int main()
{
FILE *fp;
int found = 0;
char user[20];//allow extra
char pass[20];
fp=fopen("account.txt","a");
if(fp==NULL)
{
perror ("could not open file ");
return 1;
}
/**
strcpy(s.accnum,"abcd1234");
strcpy(s.accode,"1234");
strcpy(s.fname,"john");
strcpy(s.lname,"doe");
fwrite(&s,sizeof(s),1,fp);
**/
printf("BANKING SERVICE");
printf("\nInput User: ");
fgets(user, sizeof ( user), stdin);
if ( user[strlen(user)-1] == '\n') {
user[strlen(user)-1] = '\0';//remove newline
}
printf("\nInput Pass: ");
fgets(pass, sizeof ( pass), stdin);
if ( pass[strlen(pass)-1] == '\n') {
pass[strlen(pass)-1] = '\0';//remove newline
}
while(fread(&s,sizeof(s),1,fp)==1)
{
if (strcmp(user,s.accnum) == 0 && strcmp(pass,s.accode) == 0)
{
printf("\n\nsuccess!");
found = 1;
break;
}
}
if ( found == 0)
{// after entire file has been read, report problem
printf("\n\nno match for that account and passcode!");
}
fclose(fp);
getchar();
return 0;
}
答案 1 :(得分:0)
您需要检查文件的结尾。
while( !feof( fp ) )
{
fread(&s,sizeof(s),1,fp);
if( ferror( fp ) )
{
// Error occurred
break;
}
if (strcmp(user,s.accnum) == 0 && strcmp(pass,s.accode) == 0)
{
printf("\n\nsuccess!");
}
else
{
printf("\n\nerror!");
}
}