如何用c语言写账

如何用c语言写账

#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;

}

相关推荐

MC6A遥控器的功能与特点(全方位掌控,便捷操控的MC6A遥控器)
最便宜购物软件排行榜TOP10:让你买得实惠,用得放心
365赢了不让提款

最便宜购物软件排行榜TOP10:让你买得实惠,用得放心

📅 09-27 👁️ 3489
海盗来了游戏多久了
365赢了不让提款

海盗来了游戏多久了

📅 07-14 👁️ 4252