You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

63 lines
1.7 KiB

#include "currentCustomerAccountBalance.h"
float fetchBalanceFromBalanceString(char balance_String[MAX_LENGTH]) {
float balance = 0;
char *token = strtok(balance_String, "="); // separates string to two parts
while (token != NULL) {
if (atoi(token) != 0) {
balance = atof(token); // converts string to float
break;
}
token = strtok(NULL, "=");
}
return balance;
}
float readFileAndGetAvailableBalance(FILE *file, char stringID[MAX_LENGTH]) {
float balance = 0;
bool keep_reading = true;
char buffer[MAX_LENGTH];
char balance_String[MAX_LENGTH];
while(keep_reading) {
fgets(buffer, MAX_LENGTH, file);
if (feof(file)) {
keep_reading = false;
}
else if(strstr(buffer, stringID)) {
for (int i = 0; i < 4; i++) {
fgets(buffer, MAX_LENGTH, file);
}
strcpy(balance_String, buffer);
balance = fetchBalanceFromBalanceString(balance_String);
keep_reading = false;
}
}
return balance;
}
float getAvailableAccountBalance(int user_id) {
float availableBalance = 0;
char stringID[MAX_LENGTH] = "ID=";
char user_id_as_string[MAX_LENGTH];
sprintf(user_id_as_string, "%d", user_id); // converts user_id to string
strcat(stringID, user_id_as_string);
// Now stringID is "ID=user_id"
FILE *file = fopen(CUSTOMER_DATA_FILE, "r");
if(file == 0) {
printf("Error: customer data file cannot be opened!\n");
return 0;
}
else {
availableBalance = readFileAndGetAvailableBalance(file, stringID);
}
fclose(file);
return availableBalance;
}