#define FILENAME "accounts.dat"
// Create account
void createAccount() {
struct Account a;
FILE *fp = fopen(FILENAME, "ab");
if(!fp) { printf("Error opening file.\n"); return; }
printf("Enter Account Number: "); scanf("%d", &a.accNo);
printf("Enter Name: "); scanf(" %[^\n]", a.name);
printf("Enter Initial Balance: "); scanf("%f", &a.balance);
fwrite(&a, sizeof(a), 1, fp);
fclose(fp);
printf("Account created successfully!\n");
}
// View all accounts
void viewAccounts() {
struct Account a;
FILE *fp = fopen(FILENAME, "rb");
if(!fp) { printf("No records found.\n"); return; }
printf("\nAccNo\tName\tBalance\n");
while(fread(&a, sizeof(a), 1, fp)) {
printf("%d\t%s\t%.2f\n", a.accNo, a.name, a.balance);
}
fclose(fp);
}
// Deposit money
void deposit() {
int accNo;
float amount;
struct Account a;
FILE *fp = fopen(FILENAME, "rb+");
if(!fp) { printf("No records found.\n"); return; }
printf("Enter Account Number: "); scanf("%d", &accNo);
int found = 0;
while(fread(&a, sizeof(a), 1, fp)) {
if(a.accNo == accNo) {
printf("Enter Amount to Deposit: "); scanf("%f", &amount);
a.balance += amount;
fseek(fp, -sizeof(a), SEEK_CUR);
fwrite(&a, sizeof(a), 1, fp);
printf("Amount deposited successfully! New Balance: %.2f\n", a.balance);
found = 1;
break;
}
}
if(!found) printf("Account not found.\n");
fclose(fp);
}
// Withdraw money
void withdraw() {
int accNo;
float amount;
struct Account a;
FILE *fp = fopen(FILENAME, "rb+");
if(!fp) { printf("No records found.\n"); return; }
printf("Enter Account Number: "); scanf("%d", &accNo);
int found = 0;
while(fread(&a, sizeof(a), 1, fp)) {
if(a.accNo == accNo) {
printf("Enter Amount to Withdraw: "); scanf("%f", &amount);
if(amount > a.balance) {
printf("Insufficient Balance!\n");
} else {
a.balance -= amount;
fseek(fp, -sizeof(a), SEEK_CUR);
fwrite(&a, sizeof(a), 1, fp);
printf("Withdrawal successful! New Balance: %.2f\n", a.balance);
}
found = 1;
break;
}
}
if(!found) printf("Account not found.\n");
fclose(fp);
}
// Delete account
void deleteAccount() {
int accNo;
struct Account a;
FILE *fp = fopen(FILENAME, "rb");
FILE *temp = fopen("temp.dat", "wb");
if(!fp || !temp) { printf("File error.\n"); return; }
printf("Enter Account Number to Delete: "); scanf("%d", &accNo);
int found = 0;
while(fread(&a, sizeof(a), 1, fp)) {
if(a.accNo == accNo) {
found = 1;
continue; // skip copying to delete
}
fwrite(&a, sizeof(a), 1, temp);
}
fclose(fp);
fclose(temp);
remove(FILENAME);
rename("temp.dat", FILENAME);
if(found) printf("Account deleted successfully!\n");
else printf("Account not found.\n");
}