In this tutorial, you'll build a complete Bank Account Management System in C. This is the capstone project of the file handling series — it combines everything you've learned: structs to model records, binary files for persistence, fwrite/fread to serialize and load, fseek to update records in place, and a menu-driven loop to tie it all together. You'll be able to create accounts, deposit, withdraw, and display every record, with all data surviving between program runs.
📝 Problem Statement
Build a simple Bank Account Management System in C using file handling (create, deposit, withdraw, display).
🎯 Features
The program exposes five operations through a numbered menu:
| Option | What it does |
|---|---|
| 1. Create Account | Prompts for account number, name, and initial balance; appends the new record to the file. |
| 2. Deposit | Looks up the account by number, adds the amount to the balance, and rewrites the record. |
| 3. Withdraw | Same as deposit, but subtracts — with a check that prevents overdrawing. |
| 4. Display All | Reads every record and prints a formatted table of accounts. |
| 5. Exit | Closes the program cleanly. All data remains in the file for next time. |
⚙️ How the Program Works
Each operation follows the same file-handling pattern:
- Open the file with the mode appropriate to the operation:
"ab"for create,"rb+"for deposit/withdraw (read and write),"rb"for display. - Create a struct record — for a new account, fill it from user input.
- Use
fwrite/freadto write or search for the record. - For deposit/withdraw, use
fseekto overwrite the found record in place. - Close the file so all changes reach disk.
💻 Complete C Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DATA_FILE "accounts.bin"
struct Account {
int acc_no;
char name[50];
double balance;
};
/* ---------- Helper functions ---------- */
static void clear_input(void)
{
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
}
static void create_account(void)
{
FILE *fp;
struct Account a;
printf("Enter account number: ");
scanf("%d", &a.acc_no);
clear_input();
printf("Enter account holder name: ");
fgets(a.name, sizeof(a.name), stdin);
a.name[strcspn(a.name, "\n")] = '\0';
printf("Enter initial deposit: ");
scanf("%lf", &a.balance);
fp = fopen(DATA_FILE, "ab");
if (!fp) { printf("Error: Could not open data file.\n"); return; }
fwrite(&a, sizeof(struct Account), 1, fp);
fclose(fp);
printf("Account %d created with balance %.2f.\n", a.acc_no, a.balance);
}
static void deposit(void)
{
FILE *fp;
struct Account a;
int acc_no;
double amount;
long pos;
int found = 0;
printf("Enter account number: ");
scanf("%d", &acc_no);
printf("Enter amount to deposit: ");
scanf("%lf", &amount);
fp = fopen(DATA_FILE, "rb+");
if (!fp) { printf("Error: Could not open data file.\n"); return; }
while (fread(&a, sizeof(struct Account), 1, fp) == 1)
{
if (a.acc_no == acc_no)
{
a.balance += amount;
pos = ftell(fp) - (long)sizeof(struct Account);
fseek(fp, pos, SEEK_SET);
fwrite(&a, sizeof(struct Account), 1, fp);
found = 1;
break;
}
}
fclose(fp);
if (found)
printf("Deposited %.2f. New balance: %.2f.\n", amount, a.balance);
else
printf("Account %d not found.\n", acc_no);
}
static void withdraw(void)
{
FILE *fp;
struct Account a;
int acc_no;
double amount;
long pos;
int found = 0;
printf("Enter account number: ");
scanf("%d", &acc_no);
printf("Enter amount to withdraw: ");
scanf("%lf", &amount);
fp = fopen(DATA_FILE, "rb+");
if (!fp) { printf("Error: Could not open data file.\n"); return; }
while (fread(&a, sizeof(struct Account), 1, fp) == 1)
{
if (a.acc_no == acc_no)
{
if (a.balance < amount)
{
printf("Insufficient balance. Current balance: %.2f.\n", a.balance);
fclose(fp);
return;
}
a.balance -= amount;
pos = ftell(fp) - (long)sizeof(struct Account);
fseek(fp, pos, SEEK_SET);
fwrite(&a, sizeof(struct Account), 1, fp);
found = 1;
break;
}
}
fclose(fp);
if (found)
printf("Withdrew %.2f. New balance: %.2f.\n", amount, a.balance);
else
printf("Account %d not found.\n", acc_no);
}
static void display_all(void)
{
FILE *fp;
struct Account a;
int count = 0;
fp = fopen(DATA_FILE, "rb");
if (!fp) { printf("No accounts file yet.\n"); return; }
printf("\n%-10s %-30s %-15s\n", "Acc No", "Name", "Balance");
printf("-----------------------------------------------------\n");
while (fread(&a, sizeof(struct Account), 1, fp) == 1)
{
printf("%-10d %-30s %-15.2f\n", a.acc_no, a.name, a.balance);
count++;
}
fclose(fp);
printf("-----------------------------------------------------\n");
printf("Total accounts: %d\n", count);
}
/* ---------- Main menu loop ---------- */
int main(void)
{
int choice;
do
{
printf("\n=== Bank Account Management ===\n");
printf("1. Create account\n");
printf("2. Deposit\n");
printf("3. Withdraw\n");
printf("4. Display all accounts\n");
printf("5. Exit\n");
printf("Enter choice: ");
if (scanf("%d", &choice) != 1)
{
clear_input();
printf("Invalid input.\n");
continue;
}
switch (choice)
{
case 1: create_account(); break;
case 2: deposit(); break;
case 3: withdraw(); break;
case 4: display_all(); break;
case 5: printf("Goodbye.\n"); break;
default: printf("Invalid choice.\n");
}
} while (choice != 5);
return 0;
}🖥️ Sample Output
A typical session that creates two accounts, deposits, withdraws, and displays the result:
1. Create account
2. Deposit
3. Withdraw
4. Display all accounts
5. Exit
Enter choice: 1
Enter account number: 101
Enter account holder name: Alice
Enter initial deposit: 5000
Account 101 created with balance 5000.00.
=== Bank Account Management ===
... (menu) ...
Enter choice: 1
Enter account number: 102
Enter account holder name: Bob
Enter initial deposit: 3000
Account 102 created with balance 3000.00.
=== Bank Account Management ===
... (menu) ...
Enter choice: 2
Enter account number: 101
Enter amount to deposit: 1500
Deposited 1500.00. New balance: 6500.00.
=== Bank Account Management ===
... (menu) ...
Enter choice: 3
Enter account number: 102
Enter amount to withdraw: 3500
Insufficient balance. Current balance: 3000.00.
=== Bank Account Management ===
... (menu) ...
Enter choice: 4
Acc No Name Balance
-----------------------------------------------------
101 Alice 6500.00
102 Bob 3000.00
-----------------------------------------------------
Total accounts: 2
=== Bank Account Management ===
... (menu) ...
Enter choice: 5
Goodbye.
🔍 Key Sections Explained
| Code Section | Explanation |
|---|---|
struct Account { ... }; |
Defines the record layout: an account number, a name, and a balance. Both writer and reader use the same struct. |
clear_input() |
Consumes the newline left in stdin by scanf so that the following fgets reads the name correctly. |
fopen(DATA_FILE, "ab") |
Opens for append-binary. Existing accounts are preserved; new records go to the end. |
fread(&a, sizeof(struct Account), 1, fp) |
Reads one full record per iteration. The loop stops at end of file. |
ftell(fp) - sizeof(struct Account) |
After fread advances the file position, subtracting sizeof gives the offset of the record we just read — where we need to write the updated record back. |
fseek(fp, pos, SEEK_SET); fwrite(...) |
Moves back to the start of the found record and rewrites it in place. This is the core of in-place update — no need to rewrite the whole file. |
fopen(DATA_FILE, "rb+") |
Read-and-write binary. Required for in-place updates because we need both read and write access on the same file. |
if (a.balance < amount) { ... } |
Prevents overdrawing. Without this check, a withdrawal could take the balance below zero. |
do { ... } while (choice != 5); |
The menu loop. The do..while form ensures the menu is shown at least once. |
switch (choice) { ... } |
Dispatches to the appropriate operation. This is the pattern you saw in the switch-case assignments. |
accounts.bin is the single source of truth. Never overwrite it directly with "w" mode — always use "ab" for appends and "rb+" for updates. Opening with "w" would wipe every existing account.
🧠 How the In-Place Update Works
Deposit and withdraw are the most interesting operations because they need to change a record that's already in the middle of the file. The trick is:
- Open the file in
"rb+"mode so we can both read and write. - Read records one by one with
fread. - When we find the target account, the file position is now just past the end of that record. Calculate the start of the record:
pos = ftell(fp) - sizeof(struct Account). - Call
fseek(fp, pos, SEEK_SET)to jump back to the start of the record. - Call
fwrite(&a, sizeof(struct Account), 1, fp)to overwrite the record with the updated one.
No other records are touched. This is why random-access functions are essential — without fseek and ftell, you'd have to copy the entire file to a temp file just to change one number. For a file with thousands of accounts, that would be catastrophically slow.
🚀 Possible Enhancements
This program covers the essential features. If you want to extend it (and show off in a viva), here are some natural next steps:
| Feature | What you'd add |
|---|---|
| Delete account | Copy all records except the target into a temp file, then swap (same pattern as Problem 6). |
| Search by name | Add a menu option that scans the file and prints every account whose name contains a given substring. |
| Transaction log | Append a timestamped line to a separate transactions.log file every time a deposit or withdrawal happens. |
| Duplicate account check | Before creating, scan the file for the same account number and reject duplicates. |
| Interest calculation | Add a menu option that applies a fixed interest rate to every account, updating them all in one pass. |
| Password protection | Add a hashed PIN to each account and require it before deposit/withdraw. |
🐛 Common Pitfalls
- Using
"w"instead of"ab"for creation: Every new account would erase all previous ones. Always use"ab"when adding records. - Forgetting
fseekafterfread: Without jumping back,fwritewould write the updated record after all existing ones, creating a duplicate instead of updating. - Opening
"rb"for deposit/withdraw: Read-only mode prevents writing. Use"rb+". - Leaving the newline in
name: Afterfgets, the trailing newline is part of the string. Usestrcspnorstrlento trim it. - Not checking
fopenforNULL: The program would crash on the firstfwriteif the file can't be opened. - Ignoring
fread's return value: The loop conditionfread(...) == 1handles this — a partial read means end of file or corruption. - Account number uniqueness: This program doesn't check for duplicates. Add a scan before creating if that matters.
💡 Tips & Best Practices
- Store the file name in a
#defineat the top so it's easy to change. - Trim trailing newlines from names with
strcspnorstrlen. - Compile with
gcc -Wall -Wextra -std=c11 -gto catch format-specifier mismatches (e.g.,%lfwithdouble). - For a real bank system, never store balances as
double— use integer cents or a fixed-point type to avoid floating-point errors. - Add transaction logging for auditability — a real bank system needs an immutable record of every change.
- Consider the source: this is a learning project, not production code. Real banking systems use databases, transactions, and encryption.