diff --git a/src/currentCustomerAccountBalance.c b/src/currentCustomerAccountBalance.c index 1f87d76..9d2e365 100644 --- a/src/currentCustomerAccountBalance.c +++ b/src/currentCustomerAccountBalance.c @@ -13,20 +13,12 @@ float fetchBalanceFromBalanceString(char balance_String[MAX_LENGTH]) { return balance; } -float getAvailableAccountBalance(int user_id) { +float readFileAndGetAvailableBalance(FILE *file, char stringID[MAX_LENGTH]) { + float balance = 0; bool keep_reading = true; - float availableBalance = 0; - char buffer[MAX_LENGTH]; - char stringID[MAX_LENGTH] = "ID="; - char user_id_as_string[MAX_LENGTH]; char balance_String[MAX_LENGTH]; - sprintf(user_id_as_string, "%d", user_id); // converts user_id to string - strcat(stringID, user_id_as_string); - - FILE *file = fopen("CustomerData.txt", "r"); - while(keep_reading) { fgets(buffer, MAX_LENGTH, file); if (feof(file)) { @@ -38,11 +30,33 @@ float getAvailableAccountBalance(int user_id) { fgets(buffer, MAX_LENGTH, file); fgets(buffer, MAX_LENGTH, file); strcpy(balance_String, buffer); - availableBalance = fetchBalanceFromBalanceString(balance_String); + 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("CustomerData.txt", "r"); + if(file == 0) { + printf("Erro: file cannot be opened!"); + return 0; + } + else { + availableBalance = readFileAndGetAvailableBalance(file, stringID); + } + + fclose(file); return availableBalance;