Skip to content
Tutorials Center
My learning

Topics

Lesson 112 of 135 ยท Projects

Project: Bank Account System

Build a bank account system in C - money as integer cents, strict amount parsing, enum error codes, safe transfers, and a transaction log file you can audit.

A bank account program is a favorite exercise because it looks easy and isn't. Depositing and withdrawing are one line each. The hard part is everything around them: an amount like 12.345 or -5 must be refused, a withdrawal can't take more than the balance, a transfer must change both accounts or neither, a closed account must stay closed, and every change must leave a permanent record that can be checked later. Real financial software is mostly this kind of careful bookkeeping, and C, which checks nothing for you, is a great place to learn it.

In this project you'll build a small bank in three stages. First you'll represent money correctly and parse amounts strictly. Then you'll write the account operations, each returning an error code from one enum, and test them with a driver program. Finally you'll add a command interface and a transaction log file that's written before every change and can be replayed to audit the balances. Each stage is a complete program. You'll use structures, enumerations, fixed-width integers, error handling, text files and string functions.

The plan

The program is organized around three decisions:

  1. Money is an integer number of cents (int64_t), never a double.
  2. Every operation returns a bank_status code. BANK_OK means success; anything else names exactly what went wrong, and a single function turns codes into messages.
  3. Validate first, then log, then change. An operation checks everything that could fail before touching any balance, writes the transaction to the log, and only then updates memory. A failure at any point leaves the bank unchanged.

Stage 1: money done right

Why not just use double? Because binary floating point can't represent most decimal fractions exactly. 0.10 is stored as a number slightly above one tenth, and the tiny errors add up:

C Why money is never stored in a double

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Ten deposits of 0.10 give a double of 0.99999999999999989. It still prints as 1.00 with %.2f, which makes the bug invisible until a comparison like balance == 1.00 fails or a report is off by a cent. The last line is worse: 1.15 * 100 is 114.99999999999999, and converting it to an int truncates it to 114. A program that converts user input to cents this way loses a cent on some amounts and not others. The Floating-Point Numbers lesson explains why.

Integers have none of these problems. Storing cents in an int64_t makes every amount exact and every comparison reliable, and 64 bits hold up to about 92 quadrillion dollars, more than any account needs. (Some systems need fractions of a cent, for example for currency exchange or interest; they use a smaller unit, like tenths of a cent, with the same idea.)

Parsing amounts strictly

Because amounts must become exact cents, we can't read them with strtod either: it would produce a double. parse_amount reads the digits itself:

  • It accepts digits, optionally followed by a dot and one or two decimal digits: 12, 12.5 (meaning 12.50) and 12.50.
  • It rejects everything else: a sign, a comma, a missing whole part (.50), a dot with no decimals (12.), a third decimal digit, trailing text, and zero.
  • It stops accumulating digits as soon as the value passes the limit, so even a 20-digit input can never overflow int64_t. Overflowing a signed integer would be undefined behavior; checking before each multiplication is the safe pattern.
  • It returns a bank_status, distinguishing a badly formatted amount from one that's too large, so the user gets a precise message.

format_amount goes the other way, printing cents as 1234.50 with %02 to keep the leading zero in the cents (7 cents prints as 0.07, not 0.7). It writes into a buffer the caller provides and returns that buffer, so it can be used directly inside a printf call.

The status codes for the whole project are declared in this first stage, together with their messages:

C
static const char *const status_messages[] = {
    [BANK_OK] = "ok",
    [BANK_ERR_BAD_AMOUNT] = "amount must be a positive number with at most 2 decimals",
    [BANK_ERR_AMOUNT_TOO_LARGE] = "amount exceeds the 1,000,000.00 limit per transaction",
    /* ... */
};

The [BANK_OK] = syntax is a C99 designated initializer for arrays: each message sits next to the code it belongs to, so reordering the enum can't silently mismatch them. This is how C libraries implement functions like strerror.

Each line of the Input box is one amount to test:

C Stage 1: parsing and formatting amounts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Only the first five lines are accepted. 1000000.01 is one cent over the per-transaction limit, and the 20-digit number is caught as "too large" without any overflow. Requiring a whole part (.50 is refused) is a design choice; you could accept it by allowing whole_digits == 0 when decimals follow.

Stage 2: accounts and error codes

An account holds its number, owner, balance in cents and whether it's open. The bank holds a fixed array of 100 accounts and a count:

C
typedef struct {
    int number;
    char owner[OWNER_SIZE];
    int64_t balance;            /* in cents */
    bool open;
} account;

typedef struct {
    account accounts[MAX_ACCOUNTS];
    size_t count;
} bank;

Account numbers start at 1001 and are handed out in order, so finding an account is simple arithmetic: account n lives at index n - 1001. find_account checks the range before indexing, because an unchecked index from user input is exactly how buffer overruns happen. Accounts are never removed, only marked closed, which keeps numbers stable and history intact (a real bank never reuses an account number either).

Every operation follows the same shape: look up the accounts, check every rule, and only then change the balances. Here's the transfer:

C
static bank_status bank_transfer(bank *b, int from, int to, int64_t cents)
{
    if (from == to) {
        return BANK_ERR_SAME_ACCOUNT;
    }
    account *source;
    account *target;
    bank_status status = find_open_account(b, from, &source);
    if (status == BANK_OK) {
        status = find_open_account(b, to, &target);
    }
    if (status != BANK_OK) {
        return status;
    }
    if (cents > source->balance) {
        return BANK_ERR_INSUFFICIENT_FUNDS;
    }
    if (target->balance > MAX_BALANCE_CENTS - cents) {
        return BANK_ERR_BALANCE_LIMIT;
    }
    source->balance -= cents;                       /* both or neither */
    target->balance += cents;
    return BANK_OK;
}

Because every check comes before the two updates, there's no path that takes money from one account without adding it to the other. Notice also the limit check: target->balance > MAX_BALANCE_CENTS - cents instead of target->balance + cents > MAX_BALANCE_CENTS. The rearranged form can't overflow, because both sides stay within range. That's the standard way to test a sum against a limit (Type Limits covers it, and C23's ckd_add does it for you).

find_open_account returns its result through an out-parameter (account **out) while its return value carries the status. That's the most common C convention for functions that can fail: the return value says whether it worked, the pointer parameter delivers what it produced. See Pointers to Pointers.

bank_close refuses to close an account with money in it, and a closed account rejects every later operation with its own error code. The bank itself is declared static in main: it's about 6 KB, which is fine on the stack, but a static object is zero-initialized automatically, and making it a habit for large structs avoids stack overflows when MAX_ACCOUNTS grows (Memory Layout).

To test the operations before building a user interface, stage 2 uses a test driver: a main that calls each function with good and bad arguments and prints the status. Helper functions such as deposit_text combine parsing and the operation; whichever step fails first decides the status.

C Stage 2: accounts and error codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Every rule produces its own message: the empty name, the three-decimal amount, the overdraft, the self-transfer, the unknown account 1003, closing Omar's account while it still holds 420.74 (his 320.75 plus Maya's 99.99), and depositing into a closed account. The loop at the end deposits the maximum amount until Maya's account reaches its limit: 999 deposits succeed, and the 1000th is refused before the balance could pass 1,000,000,000.00. The report shows the final state, with the closed account kept for the record.

Stage 3: commands and the transaction log

The final stage adds two things: a command interpreter reading from the Input box, and a log file of every transaction.

The transaction log

When the program starts, it opens transactions.log for writing. Every operation calls write_log after its checks pass and before it changes any balance:

C
static bank_status write_log(bank *b, const char *type, int from, int to, int64_t cents)
{
    if (fprintf(b->log, "%ld,%s,%d,%d,%" PRId64 "\n", b->next_entry, type, from, to, cents) < 0
        || fflush(b->log) != 0) {
        return BANK_ERR_LOG;
    }
    b->next_entry++;
    return BANK_OK;
}

Each line records a sequence number, the type, the source and destination accounts (0 when there's none) and the amount in cents, for example 6,transfer,1001,1002,9999. The order matters. If writing the log fails, for instance because the disk is full, the operation returns BANK_ERR_LOG and the balance is never changed: memory and the log can't disagree. This idea, write-ahead logging, is how databases survive crashes. fflush after each line pushes the entry out of the stdio buffer immediately, so a crash a moment later can't lose a transaction that the user was told succeeded.

Real systems add a timestamp to each entry (with time and strftime, see Time and Date). We leave it out so the output is the same on every run.

Reading the log back

Two commands read the file while it's still open for writing, which works because fflush has already written every entry. They open it a second time with mode "r" and parse each line with sscanf:

C
sscanf(line, "%ld,%15[^,],%d,%d,%" SCNd64, &e->entry, e->type, &e->from, &e->to, &e->cents) == 5

The %15[^,] conversion reads up to 15 characters that aren't commas into the type array (16 bytes with the terminator), so a corrupt line can't overflow it. SCNd64 is the <inttypes.h> macro for reading an int64_t, the input counterpart of PRId64. Checking that sscanf returned 5 skips any malformed line.

  • history N prints every entry involving account N, describing transfers from that account's point of view ("from 1001" or "to 1002").
  • audit replays the whole log into a fresh array of balances, subtracting amounts from each source and adding them to each destination, and compares the result with the balances in memory. If anyone ever changed a balance without logging it, the audit would report a mismatch. That's exactly what auditors do with real ledgers.

The command interpreter

run_command handles open specially, because the owner's name can contain spaces: everything after open is the name. For every other command it splits the line into words with strtok and checks the word count and each account number before calling the bank functions. Any line that doesn't fit a known pattern prints a usage summary instead of guessing what the user meant.

Command Example
open NAME open Maya Lopez
deposit N AMOUNT / withdraw N AMOUNT deposit 1001 1500
transfer FROM TO AMOUNT transfer 1001 1002 99.99
balance N, close N, history N history 1002
report, audit
C Stage 3: the bank with a transaction log

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The session opens two accounts, moves money between them and tries four invalid operations, each refused with a precise reason and no change to any balance. history 1002 lists Omar's three entries: the opening (#2), his deposit (#4) and the transfer from Maya (#6). Note the gaps in the numbering: entries #1, #3 and #5 belong to Maya. Omar then withdraws everything, closes the account, and a later withdrawal is refused. The report shows both accounts, and audit replays all 8 log entries and confirms that every balance in memory matches the log. The failed operations never reached the log, which is why there are only 8 entries for 13 attempted operations.

Tip: Try to break the bank. Withdraw 0, deposit 1e3 or 12,50, transfer to account 0, type deposit 1001 without an amount or transfer 1001 1002 5 extra, or open an account with a 50-character name. None of these should change a balance, and audit should always say the balances match.

Design lessons from this project

  • Pick representations that make bugs impossible. Integer cents eliminate an entire class of rounding bugs that no amount of careful coding with double could fully avoid.
  • One enum of error codes, one message table. Callers test status != BANK_OK; the user interface turns codes into text in one place. Adding a new error is one enum constant and one message.
  • Check everything, then act. All validation happens before the first change, so there's no half-finished operation to undo.
  • Log before you change. A durable record written first means memory can always be reconstructed or verified.
  • Separate the core from the interface. The bank functions never print anything and never read input. Stage 2 drove them from a test program and stage 3 from commands, without changing a single line in them. You could put them in bank.c with a bank.h header (Multi-File Programs) and reuse them in a GUI or a server.

Ideas to extend it

  • Persistence: at startup, open the log in append mode ("a") and replay it to restore every account, so the bank survives restarts. The audit code already does most of the work.
  • Interest: a month-end command that adds interest in integer cents with a clear rounding rule (for example, round half up), logging one entry per account.
  • Overdraft limits per account, stored in the struct, checked in bank_withdraw and bank_transfer.
  • Thousands separators in format_amount: 1,199.51.
  • A PIN per account, stored as a hash rather than plain text, required for withdrawals.
  • Concurrent tellers: run several threads issuing transfers and protect the bank with a mutex. Lock ordering (always lock the lower account number first) prevents deadlock, as described in Multithreading.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does (int)(1.15 * 100) give in C with IEEE 754 doubles?

    1.15 can't be stored exactly; the product is 114.99999999999999, and converting to int truncates it to 114. That's why money is kept in integer cents.
  2. 2. Why does the deposit check use balance > MAX_BALANCE_CENTS - cents instead of balance + cents > MAX_BALANCE_CENTS?

    Both operands are within range and the subtraction can't overflow. Computing the sum first could overflow a signed integer, which is undefined behavior.
  3. 3. In this design, what happens if write_log fails during a withdrawal?

    The log is written before the balance changes, so a failed write stops the operation and memory and log stay consistent.
  4. 4. Why does history work while the log file is still open for writing?

    Without fflush, recent entries could still be sitting in the stdio buffer and the reader would miss them.
  5. 5. What does the sscanf conversion %15[^,] do?

    A scanset with a width limit is the safe way to read a delimited string field with the scanf family.

Summary

  • Store money as integer cents in int64_t; double can't represent most decimal amounts exactly.
  • Parse amounts digit by digit with strict rules and an overflow-safe limit check; format with %02 for the cents.
  • Return an enum status from every operation and map codes to messages with a designated-initializer array.
  • Validate everything before changing anything, and test limits in a form that can't overflow.
  • Write each transaction to a log and fflush it before applying the change; replay the log to audit balances.
  • Keep the bank core free of input and output so it can be driven by tests, commands or any other interface.

Next: Project: Text Analyzer