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.

64 lines
1.7 KiB

  1. #include "currentCustomerAccountBalance.h"
  2. //#include "_file_information.h"
  3. float fetchBalanceFromBalanceString(char balance_String[MAX_LENGTH]) {
  4. float balance = 0;
  5. char *token = strtok(balance_String, "="); // separates string to two parts
  6. while (token != NULL) {
  7. if (atoi(token) != 0) {
  8. balance = atof(token); // converts string to float
  9. break;
  10. }
  11. token = strtok(NULL, "=");
  12. }
  13. return balance;
  14. }
  15. float readFileAndGetAvailableBalance(FILE *file, char stringID[MAX_LENGTH]) {
  16. float balance = 0;
  17. bool keep_reading = true;
  18. char buffer[MAX_LENGTH];
  19. char balance_String[MAX_LENGTH];
  20. while(keep_reading) {
  21. fgets(buffer, MAX_LENGTH, file);
  22. if (feof(file)) {
  23. keep_reading = false;
  24. }
  25. else if(strstr(buffer, stringID)) {
  26. for (int i = 0; i < 4; i++) {
  27. fgets(buffer, MAX_LENGTH, file);
  28. }
  29. strcpy(balance_String, buffer);
  30. balance = fetchBalanceFromBalanceString(balance_String);
  31. keep_reading = false;
  32. }
  33. }
  34. return balance;
  35. }
  36. float getAvailableAccountBalance(int user_id) {
  37. float availableBalance = 0;
  38. char stringID[MAX_LENGTH] = "ID=";
  39. char user_id_as_string[MAX_LENGTH];
  40. sprintf(user_id_as_string, "%d", user_id); // converts user_id to string
  41. strcat(stringID, user_id_as_string);
  42. // Now stringID is "ID=user_id"
  43. FILE *file = fopen(CUSTOMER_DATA_FILE, "r");
  44. if(file == 0) {
  45. printf("Error: customer data file cannot be opened!\n");
  46. return 0;
  47. }
  48. else {
  49. availableBalance = readFileAndGetAvailableBalance(file, stringID);
  50. }
  51. fclose(file);
  52. return availableBalance;
  53. }