user7626621
user7626621

Reputation:

Reading from a file error

This is a c program that read from a file and prints informaton based on "acc_num". But the problem is that it only accepts the first acc_num in the file Why is that ? I wanted it to search throught the entire file for a specific acc_num.

 #include < stdio.h >
 #include < string.h >
 #include < conio.h >
 struct CUSTOMER {
char fname[50];
char lname[50];
char address[100];
char con_num[50];
char email[50];
char acc_num[999]; //account number 
  };

struct CUSTOMER information[999];
int main() {
FILE * fptr;
fptr = fopen("customers.dat", "r");
int i;
int x;
char acc[50];

for (x = 0; x < 1; x++) {
printf("Enter account number:");
scanf("%s", & acc);
getchar();

for (x = 0; x < 1; x++) {

  fscanf(fptr, " %s\n", information[x].acc_num);
  fscanf(fptr, " %s\n", information[x].fname);
  fscanf(fptr, " %s\n", information[x].lname);
  if (strcmp(information[x].acc_num, acc) == 0) {
    printf("%s%s%s", information[x].acc_num, information[x].fname, information[x].lname);
    getchar();
  }
 }
 }
  getch();
 return 0;
 }

Upvotes: 0

Views: 28

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140276

scanf("%s", & acc); doesn't work / is undefined behaviour and acc is never initialized (at best), and you cannot find the pattern in your file.

In the case of strings scanf needs a pointer/array of chars, and you already provide it with acc.

You have to do scanf("%s", acc);

Also, your inner loop goes up to 1. It only reads one record! And once the file is read, there's no data to read anymore. You should open the file and scan through it every time and stop when you reach end of file.

Upvotes: 2

Related Questions