I've coded a basic ATM machine program which contains the features like create an account, check balance, do transactions...etc but it's not completed though. I've used file to store the data and to read it. The read_account fucntion to read, write_account function to create new account and no_of_accounts to get number of accounts in the file all working properly. The problem is with find_account_number which should take an account number as it's parameter and return index at which the account number is.
#include <stdio.h>
#include <stdlib.h>
#define MAX_act 100
typedef struct{
long account_number;
int CVV;
int PIN;
float balance;
long phone_number;
} act;
void write_account(long account_number, int CVV, int PIN, long phone_number)
{
FILE *f;
act *account = (act*) malloc(sizeof(act));
f = fopen("account_data", "a");
*account = (act) { account_number, CVV, PIN, 0, phone_number};
fprintf(f, "%ld %d %d %.2f %ld\n", account->account_number, account->CVV, account->PIN, account->balance, account->phone_number);
fclose(f);
}
act* read_accounts(void){
FILE *f;
int i = 0;
f = fopen("account_data", "r");
act *accounts = (act*) malloc(sizeof(act)*MAX_act);
while(fscanf(f, "%ld %d %d %f %ld", &accounts[i].account_number, &accounts[i].CVV, &accounts[i].PIN, &accounts[i].balance, &accounts[i].phone_number) == 5){
i++;
}
fclose(f);
return accounts;
}
int no_of_accounts(void){
FILE *f;
int i = 0;
act *accounts;
f = fopen("account_data", "r");
while(fscanf(f, "%ld %d %d %f %ld", &accounts->account_number, &accounts->CVV, &accounts->PIN, &accounts->balance, &accounts->phone_number) == 5)
i++;
free(accounts);
return i;
}
int find_account_no(long account_number, int no_of_accounts, act *accounts){
int i = 0;
act *account = accounts;
printf("yes, it's called\n");
for(i=0; i< no_of_accounts; i++){
printf("%ld\n", account[i].account_number);
if(account[i].account_number == account_number)
return i;
}
return -1;
}
int main(){
//write_account(123, 111, 222, 939);
//write_account(321, 111, 222, 939);
//write_account(123, 111, 222, 939);
find_account_no(123, no_of_accounts(), read_accounts());
printf("%d\n", no_of_accounts());
}
so in the function find_account_number I've passed a account number, no 0f accounts and the pointer to an array in which the account data is stored using read_accounts function. Where's the bug? The output is printing not expectedly.