#include
#include
#include
typedef struct {
char name[50];
float amount;
} Account;
void add_account(Account accounts, int *size, const char *name, float amount) {
*size += 1;
*accounts = realloc(*accounts, sizeof(Account) * (*size));
if (*accounts == NULL) {
printf("Memory reallocation failed!n");
exit(1);
}
strcpy((*accounts)[*size - 1].name, name);
(*accounts)[*size - 1].amount = amount;
}
void save_accounts(Account *accounts, int size, const char *filename) {
FILE *file = fopen(filename, "w");
if (file == NULL) {
printf("Error opening file!n");
return;
}
for (int i = 0; i < size; i++) {
fprintf(file, "%s %fn", accounts[i].name, accounts[i].amount);
}
fclose(file);
}
void load_accounts(Account accounts, int *size, const char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file!n");
return;
}
char name[50];
float amount;
while (fscanf(file, "%s %f", name, &amount) == 2) {
add_account(accounts, size, name, amount);
}
fclose(file);
}
int main() {
Account *accounts = NULL;
int size = 0;
add_account(&accounts, &size, "Rent", 1200.0);
add_account(&accounts, &size, "Groceries", 250.0);
add_account(&accounts, &size, "Internet", 60.0);
save_accounts(accounts, size, "accounts.txt");
free(accounts);
accounts = NULL;
size = 0;
load_accounts(&accounts, &size, "accounts.txt");
for (int i = 0; i < size; i++) {
printf("Account: %s, Amount: %.2fn", accounts[i].name, accounts[i].amount);
}
free(accounts);
return 0;
}