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.

62 lines
1.7 KiB

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