Reputation: 39
doing this simple program. This is just the firt part of a banking service program. Somehow, I am stuck with this fread()
. I cant compare the input of the user and my database. When my program starts, after I input user and pass it kinda 'hang' or 'freeze' then a popup will appear and says "end program". BTW I am using 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();
}
Upvotes: 0
Views: 963
Reputation: 8286
In the loop check for successful match. If no match is found, the found
flag will still be zero. Then report the problem after the while loop has completed.
fgets will include the newline so it has to be removed before comparing to the contents of the file as the commented section does not show any newlines.
#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;
}
Upvotes: 1
Reputation: 107121
You need to check for end of file.
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!");
}
}
Upvotes: 0