Wednesday, November 25, 2026
HomeC ProgrammingFull Undertaking with Supply Code

Full Undertaking with Supply Code


Add ten cents to a C double ten occasions and print the entire to 17 vital digits: you get 0.99999999999999989, and whole == 1.0 is fake. That small error is why cash is the very first thing to get proper in a financial institution administration system in C. Many scholar variations of this mission retailer balances as float, learn names with scanf("%s") and rewrite the entire knowledge file on each save. Every of these selections can lose a buyer’s cash with none warning.

This text walks by a whole financial institution administration system written in normal C11: financial savings and present accounts, deposits, withdrawals, transfers, month-to-month curiosity, statements and a every day report. Each quantity is stored in entire cents, and each change goes right into a ledger file that this system checks line by line every time it begins. This system was constructed and examined for this text on Ubuntu 24.04 with GCC 13.3 and Clang 18.1 beneath -std=c11 and -std=c17 with -Wall -Wextra -pedantic -Werror and nil warnings, and on Home windows with Visible Studio’s compiler (MSVC) at /W4 /WX. All 27 exams cross, together with beneath AddressSanitizer and UndefinedBehaviorSanitizer, and each output block under is captured from an actual run. In case you are new to C tasks, the C mini tasks for rookies are a gentler place to begin; this one is the following step up.

What Is a Financial institution Administration System in C?

A financial institution administration system in C is a console program that retains buyer accounts and the transactions on them: it opens and closes accounts, information deposits, withdrawals and transfers, and prints balances and statements. A well-built one shops cash as entire cents, saves each change to a file, and refuses any operation that breaks the financial institution’s guidelines.

The model here’s a teller’s program for a small financial institution. It runs in any terminal, makes use of solely the C normal library, and builds with GCC, Clang and Visible Studio. The supply is break up into seven .c information with a header every, which is how bigger C packages are organized and what makes the code testable.

One algorithm for each change The menu and the loader construct the identical Entry and ask the identical perform

On the menu: a brand new entry 1. Learn the teller’s solutions 2. Construct an Entry 3. bank_prepare(): quantity, balances

At start-up and –confirm 1. Learn one ledger line 2. line_to_entry(): its fields 3. Verify the entry quantity

bank_check() • the account exists and is open • the quantity is 0.01 to 1,000,000.00 • the overdraft and the every day money restrict • curiosity as soon as a month, to the cent • the steadiness on the road matches the replay

RULE_OK?

Sure: ledger_append() writes the road, then bank_apply() modifications reminiscence No: inform the teller, save nothing

Sure: bank_apply() replays it, then the following line is learn No: “FILE line N: REASON”, exit 2

Determine 1: Each change, from the menu or from the ledger file, passes the identical bank_check() guidelines earlier than it touches a steadiness.

Options and Banking Guidelines

This system enforces these guidelines in all places: on the menu, and once more when it reloads its knowledge file.

Characteristic Rule on this program
Account sorts Financial savings (3.00% curiosity a yr, paid month-to-month, by no means under 0.00) and present (no curiosity, overdraft all the way down to -500.00)
Account numbers Begin at 100001 and go up by one; a closed account retains its quantity, so no quantity is reused
Opening an account Holder identify of two to 30 characters, handle of 1 to 50 (printable characters solely), opening deposit of not less than 1,000.00
Deposits and withdrawals 0.01 to 1,000,000.00 at a time
Day by day money restrict At most 5,000.00 withdrawn from one account per day; transfers don’t depend
Transfers Between two totally different open accounts, written as one ledger line, so they’re by no means half executed
Curiosity Posted as soon as per account per calendar month, rounded half as much as the cent
Steadiness restrict No steadiness above 999,999,999.99
Closing an account Solely when the steadiness is strictly 0.00, after a y/n affirmation; the historical past stays
Stories Account listing with totals, search by identify, statements with a working steadiness, every day transaction report

There’s intentionally no login or PIN. Storing a PIN in a textual content file teaches a harmful behavior, and correct password hashing wants a cryptography library; the part on extending the mission reveals tips on how to add one safely.

The right way to Construct and Run the Undertaking

Obtain or clone the mission folder from GitHub (linked in Supply Code and Exams), open a terminal in it, and compile each file in src collectively.

GCC or Clang (Linux, macOS, WSL, or MinGW on Home windows):

gcc -std=c11 -Wall -Wextra -o bank_management src/*.c
./bank_management

Visible Studio, from a Developer Command Immediate:

cl /W4 /Fe:bank_management.exe src*.c
bank_management.exe

CMake, which additionally builds and runs the exams:

cmake -S . -B construct && cmake --build construct && ctest --test-dir construct --output-on-failure

In Code::Blocks or Dev-C++, create an empty console mission and add all seven .c information from src to it. The commonest construct error with a multi-file mission is an “undefined reference” from the linker, naming a perform resembling bank_init. It means one of many .c information was disregarded of the mission.

This system accepts three choices, in any order:

Choice What it does
--file NAME Use one other ledger file as a substitute of financial institution.txt
--today YYYY-MM-DD Repair the date, so a take a look at offers the identical consequence each day
--verify Verify the ledger, print a one-line abstract and exit with out the menu

A Pattern Session

Here’s a teller opening a present account. The primary opening deposit is under the minimal, so this system asks once more. (The menu between steps is disregarded of those excerpts; it’s printed earlier than each selection.)

Select an possibility (0-11): 1
Holder identify: Ben Kim
Handle: 4 Mill Lane
Account sort (1 = Financial savings, 2 = Present): 2
Opening deposit: 999.99
The opening deposit have to be not less than 1,000.00.
Opening deposit: 2500.50
Opened present account 100002 for Ben Kim with 2,500.50.

Quantities are learn as textual content and checked earlier than something occurs. A 3rd decimal, a minus signal and nil are all refused with the identical message:

Select an possibility (0-11): 2
Account quantity: 100001
Quantity: 12.505
Please enter an quantity from 0.01 to 1,000,000.00, for instance 250 or 250.75.
Quantity: -5
Please enter an quantity from 0.01 to 1,000,000.00, for instance 250 or 250.75.
Quantity: 0
Please enter an quantity from 0.01 to 1,000,000.00, for instance 250 or 250.75.
Quantity: 100
Deposited 100.00 to 100001. New steadiness: 1,850.75.

A present account can go overdrawn, however solely by 500.00. Account 100002 began with 2,500.50 and has simply withdrawn 2,900.00, so its steadiness is -399.50 and solely 100.50 is left to take out:

Select an possibility (0-11): 3
Account quantity: 100002
Quantity: 100.51
Inadequate funds: 100002 has 100.50 accessible, together with the five hundred.00 overdraft.

The every day money restrict works the identical means. Account 100003 has already withdrawn 4,000.00 right this moment, so 1,000.01 is refused. Requested for precisely 1,000.00 subsequent, this system pays it, as a result of reaching the restrict is allowed:

Select an possibility (0-11): 3
Account quantity: 100003
Quantity: 1000.01
Day by day withdrawal restrict: 100003 can withdraw 1,000.00 extra right this moment.

Each message names the rule and the quantity that issues, so the teller is aware of what to do subsequent with out studying the code.

How the Program Is Organized

This system is break up by job, not by menu possibility. Every file has a header that declares solely what different information want; all the things else is static and invisible exterior its file.

File Strains Job
primary.c 673 Command line, start-up checks, the menu loop and one handler per menu possibility
ledger.c 438 The ledger file: writing an entry as a line, studying a line again, loading and checking the entire file
financial institution.c 369 The financial institution’s guidelines, and the one code that modifications a steadiness
report.c 266 Account listing, search, statements and the every day report
enter.c 171 Protected keyboard enter: entire numbers, textual content, quantities, sure/no and dates
cash.c 120 Parsing and printing quantities, and the curiosity calculation
date.c 98 Parsing, evaluating and printing dates

The headers add 226 traces, for two,361 in all. The feedback take a big share of that, as a result of each perform has a block above it saying what it does, what it returns and which rule it enforces.

The break up pays off in testing. Every little thing besides primary.c is constructed right into a small library, and the unit exams hyperlink that very same library with out the menu. A take a look at can name bank_check() on a financial institution in-built reminiscence and examine the precise rule it breaks, with no typing concerned.

financial institution.c has yet one more job: it’s the solely file allowed to alter a steadiness. primary.c and report.c can learn an account, however each change goes by bank_check(), which decides whether or not an entry is allowed, and bank_apply(), which applies it. Determine 1 reveals that path.

Storing Cash as Entire Cents

A double can not maintain 0.10 precisely. It shops the closest binary fraction, and the tiny errors add up, which is how ten deposits of ten cents turn out to be 0.99999999999999989. Monetary software program normally avoids this by storing integers, and so does this program:

typedef lengthy lengthy Cents;                 /* cash in entire cents, by no means float/double */

A steadiness of 1,850.75 is the integer 185075. Including, subtracting and evaluating integers is precise, and a lengthy lengthy holds not less than 9.2 × 1018, excess of the biggest steadiness this system permits.

The arduous half is studying an quantity that an individual sorts. strtod() returns a double, which brings the error straight again, and it additionally accepts 1e3, nan and hexadecimal. So money_parse() reads the digits itself:

/* Reads an quantity typed by an individual, resembling "250", "250.7" or " 250.75 ",
 * into *out as cents. Guidelines: optionally available areas or tabs earlier than and after; 1 to
 * 7 digits; then optionally a degree adopted by precisely 1 or 2 digits.
 * Nothing else is allowed: no signal, no hundreds commas, no exponent.
 * The worth have to be from 0.01 to 1,000,000.00 (MAX_AMOUNT).
 * Returns 1 and units *out if the textual content is legitimate, in any other case returns 0 and
 * leaves *out unchanged.
 *
 * Why not strtod()? It returns a double, so "0.29" would come again as
 * 0.28999999999999998 and a careless (lengthy lengthy)(x * 100) offers 28 cents.
 * strtod() additionally accepts "1e3", "nan", "inf" and hexadecimal. Constructing the
 * worth digit by digit avoids each a type of surprises.
 *
 * Overflow is unattainable: at most 7 + 2 digits are ever amassed, so
 * the worth stays under 10^9, far inside an extended lengthy. */
int money_parse(const char *textual content, Cents *out)
{
    const char *p = textual content;
    Cents worth = 0;
    int digits = 0;

    whereas (*p == ' ' || *p == 't')
        p++;
    whereas (isdigit((unsigned char)*p)) {
        if (++digits > MAX_WHOLE_DIGITS)
            return 0;                       /* too many digits: cease earlier than any overflow */
        worth = worth * 10 + (*p - '0');
        p++;
    }
    if (digits == 0)
        return 0;                           /* ".5", "-5", "+5", "nan" and "" find yourself right here */
    worth *= 100;                           /* entire items to cents */
    if (*p == '.') {
        p++;
        if (!isdigit((unsigned char)*p))
            return 0;                       /* "250." */
        worth += (*p - '0') * 10;           /* tenths */
        p++;
        if (isdigit((unsigned char)*p)) {
            worth += *p - '0';              /* hundredths */
            p++;
        }
        if (isdigit((unsigned char)*p))
            return 0;                       /* "12.505": a 3rd decimal */
    }
    whereas (*p == ' ' || *p == 't')
        p++;
    if (*p != '')
        return 0;                           /* "1,000", "1e3", "12abc" */
    if (worth < 1 || worth > MAX_AMOUNT)
        return 0;                           /* "0", "0.00", "1000000.01" */
    *out = worth;
    return 1;
}

The perform counts digits because it goes, so the worth can by no means overflow: at most seven entire digits and two decimals are ever added up. Each rejected enter within the pattern session above (12.505, -5, 0) stops at one of many return 0 traces, and the touch upon every line names the enter that reaches it.

Printing goes the opposite means. money_format() turns 185075 into 1,850.75, including a comma each three digits and all the time two decimals. The ledger file shops plain integers resembling 185075, as a result of the file is learn by this system; solely the display screen is formatted for individuals.

The identical method to enter runs by enter.c: each reply is learn as a complete line with fgets(), then checked. Nothing makes use of scanf(), so a typing mistake can by no means go away unread characters behind to be taken as the reply to the following query. Defensive programming in C covers this behavior intimately.

The Ledger: Recording What Occurred, Not the Steadiness

Most financial institution tasks hold one document per account and overwrite its steadiness after every transaction. This program by no means shops a steadiness within the file in any respect. It retains a ledger: one line per factor that occurred, added to the top of the file and by no means modified afterwards. The balances are rebuilt by replaying each line every time this system begins. Martin Fowler describes the overall sample as occasion sourcing: each change to the state is captured as a sequence of occasions.

These are the primary traces of the ledger after the pattern session:

# MYCPLUS financial institution ledger v1
1|2026-12-01|OPEN|100001|S|150000|Ana Lopez|12 Harbour Street, Springfield
2|2026-12-01|OPEN|100002|C|250050|Ben Kim|4 Mill Lane
3|2026-12-01|OPEN|100003|S|100000|Carla Diaz|9 Elm Road
4|2026-12-01|DEP|100001|25075|175075

Every line begins with its entry quantity and date, then the sort, then the fields for that sort:

Kind Fields after quantity and date That means
OPEN account, S or C, quantity, holder, handle A brand new account and its opening deposit
DEP account, quantity, steadiness after Money deposit
WDL account, quantity, steadiness after Money withdrawal
XFER from, to, quantity, each balances after Switch between two accounts
INT account, month, quantity, steadiness after Month-to-month curiosity
EDIT account, holder, handle New holder identify or handle
CLOSE account Account closed

Holder names and addresses could not include |, so splitting a line at each | is all the time protected; forbidding the separator is less complicated than quoting it. They could not include management characters both, as a result of a reputation is printed to the terminal as it’s, and an escape sequence hidden in a reputation may clear the display screen or recolor the textual content.

In reminiscence, one line turns into an Entry. It’s a “tagged struct”: the sort area says which of the opposite fields imply one thing.

/* One line of the ledger: one thing that occurred.
 *
 * This can be a "tagged struct": sort is the tag, and it says which of the
 * different fields imply one thing (the touch upon every area lists the categories
 * that use it). The unused fields are merely 0 or empty. A union may
 * overlap the fields of various sorts and save reminiscence, however then studying
 * the unsuitable member is undefined conduct that no compiler warns about. A
 * plain struct of about 150 bytes is clearer and all the time protected to learn. */
typedef struct {
    lengthy        seq;                  /* 1, 2, 3, ... */
    Date        date;
    EntryType   sort;
    int         account;              /* the account, or the supply of a switch */
    int         different;                /* switch goal; 0 in any other case */
    AccountType account_type;         /* OPEN solely */
    Cents       quantity;               /* OPEN, DEPOSIT, WITHDRAW, TRANSFER, INTEREST */
    Cents       balance_after;        /* account's steadiness after this entry */
    Cents       other_balance_after;  /* TRANSFER solely: goal's steadiness after */
    int         month;                /* INTEREST solely: 202612 */
    char        holder[NAME_SIZE];    /* OPEN and EDIT */
    char        handle[ADDRESS_SIZE];/* OPEN and EDIT */
} Entry;

Because the remark says, a union would save reminiscence at the price of security. At 152 bytes per entry, a plain construction in C is the higher commerce. The sort itself is an enum in C, and so are the account sort and the rule codes under.

As a result of the ledger retains the complete historical past, some values by no means must be saved. How a lot has an account withdrawn right this moment? This system provides it up from the ledger:

/* Returns the entire withdrawn in money from account quantity on day.
 * That is labored out from the ledger, not saved: there is no such thing as a "withdrawn
 * right this moment" counter to neglect to reset at midnight. Entries are in date
 * order, so the loop walks again from the latest and stops on the first
 * entry earlier than day. Transfers usually are not money, so they don't depend. */
Cents bank_withdrawn_on(const Financial institution *financial institution, int quantity, Date day)
{
    Cents whole = 0;

    for (size_t i = bank->entry_count; i > 0; i--) {
        const Entry *e = &bank->entries[i - 1];
        if (date_compare(e->date, day) < 0)
            break;
        if (e->sort == ENTRY_WITHDRAW && e->account == quantity && date_compare(e->date, day) == 0)
            whole += e->quantity;
    }
    return whole;
}

Nothing wants resetting at midnight, and the entire can by no means drift out of step with the transactions, as a result of it’s computed from them every time.

The trade-off is start-up time: each entry because the financial institution opened is replayed. In observe that’s quick. A take a look at ledger of 100,011 entries, about 4 years of a busy department with 200 accounts, loaded and handed each examine in 30 to 35 milliseconds on the take a look at machine. A system with a long time of historical past would retailer a snapshot of each steadiness on the finish of every month and replay solely the entries after it.

One Set of Guidelines for the Menu and the Loader

Each change, whether or not a teller sorts it or the loader reads it from the file, is checked by the identical perform. bank_check() returns RULE_OK or the primary rule the entry breaks:

/* Decides whether or not entry could also be added to the financial institution, and returns RULE_OK or
 * the primary rule it breaks. The checks run on this order:
 *   1. the date shouldn't be sooner than the earlier entry's date;
 *   2. the foundations for such a entry (listed within the README);
 *   3. balance_after (and other_balance_after) equal what making use of the
 *      entry would actually produce.
 *
 * One algorithm for 2 jobs: the menu calls this earlier than writing an
 * entry, and the loader calls it for each line it replays. So a ledger
 * edited by hand can not sneak in an overdraft the menu would refuse.
 * Step 3 can solely fail for entries learn from a file, as a result of the menu
 * fills these fields with bank_prepare(). */
Rule bank_check(const Financial institution *financial institution, const Entry *entry)
{
    const Account *a = NULL, *b = NULL;

    if (bank->entry_count > 0 &&
        date_compare(entry->date, bank->entries[bank->entry_count - 1].date) < 0)
        return RULE_DATE_BACKWARDS;

    if (entry->sort == ENTRY_OPEN)  subsequent > LAST_ACCOUNT)
            return RULE_WRONG_NUMBER;
        if (!amount_ok(entry->quantity))
            return RULE_BAD_AMOUNT;
        if (entry->quantity < MIN_OPENING)
            return RULE_OPENING_TOO_SMALL;
        if (!bank_text_ok(entry->holder, MIN_NAME_LENGTH, NAME_SIZE) 

    /* Each different entry wants an current, open account. */
    a = bank_find_const(financial institution, entry->account);
    if (a == NULL)
        return RULE_NO_ACCOUNT;
    if (a->is_closed)
        return RULE_CLOSED;

    swap (entry->sort) 

    /* Step 3: the balances written within the entry have to be the actual ones. */
    if (entry->sort != ENTRY_EDIT && entry->sort != ENTRY_CLOSE &&
        entry->balance_after != bank_balance_after(financial institution, entry, 0))
        return RULE_BALANCE_MISMATCH;
    if (entry->sort == ENTRY_TRANSFER &&
        entry->other_balance_after != bank_balance_after(financial institution, entry, 1))
        return RULE_BALANCE_MISMATCH;
    return RULE_OK;
}

Utilizing one perform for each jobs closes a spot that’s straightforward to overlook. If the menu checked the overdraft however the loader didn’t, anybody with a textual content editor may add a withdrawal the menu would have refused, and this system would settle for it on the following begin. Right here a line within the file has to cross precisely the checks the teller’s enter passes.

The rule codes are an enum. primary.c turns every code right into a message for the teller (“Inadequate funds: 100002 has 100.50 accessible, together with the five hundred.00 overdraft.”), and ledger.c turns the identical code right into a file error (“this could take account 100002 under its restrict”).

The final examine is the one solely a file can fail. The menu fills within the balance-after fields itself with bank_prepare(), so they’re all the time proper. A line learn from the file should carry the steadiness that replaying it actually produces, which is how the loader spots an edited quantity (proven later).

Write to the File First, Then Change Reminiscence

Each menu possibility that modifications knowledge takes the identical six steps: learn the teller’s solutions, construct an Entry, let bank_prepare() fill within the entry quantity and balances, ask bank_check(), append the road to the file, and solely then apply it in reminiscence. Right here is the withdrawal handler:

/* Choice 3: pays money out of an open account, inside its accessible cash
 * (the overdraft included) and the every day money restrict.
 * Returns 0 if enter ended, in any other case 1. */
static int do_withdraw(Teller *t)
{
    const Account *a;
    Entry e;
    char error[ERROR_SIZE], quantity[MONEY_TEXT_SIZE], steadiness[MONEY_TEXT_SIZE];

    if (!read_account(t, "Account quantity: ", 0, &a))
        return 0;
    if (a == NULL)
        return 1;
    e = new_entry(t, ENTRY_WITHDRAW, a->quantity);
    if (!read_money("Quantity: ", &e.quantity))
        return 0;
    Rule rule = prepare_and_check(t, &e);
    if (rule != RULE_OK) {
        clarify(t, &e, rule);
        return 1;
    }
    if (!save_entry(t, &e, error, sizeof error))
        return 1;
    money_format(e.quantity, quantity, sizeof quantity);
    money_format(e.balance_after, steadiness, sizeof steadiness);
    printf("Withdrew %s from %d. New steadiness: %s.n", quantity, e.account, steadiness);
    return 1;
}

The order of the final two steps issues, and save_entry() enforces it:

/* Write first, then change reminiscence: appends entry to the ledger file and,
 * provided that that labored, applies it to the financial institution in reminiscence.
 *
 * The alternative order is harmful: if reminiscence modified first and the write
 * then failed, the display screen would present cash that the file doesn't have,
 * and the following start-up would silently "lose" it.
 * Returns 1 on success. If the write fails, prints
 * "Couldn't save: REASON. Nothing was modified.", leaves error set and
 * returns 0. If reminiscence runs out after the write, reminiscence and file not
 * agree, so this system stops; the following begin reloads the file, which is
 * appropriate. */
static int save_entry(Teller *t, const Entry *entry, char *error, size_t error_size)
{
    if (!ledger_append(t->path, entry, t->financial institution.entry_count == 0, error, error_size)) {
        if (entry->sort != ENTRY_INTEREST)
            printf("Couldn't save: %s. Nothing was modified.n", error);
        return 0;
    }
    if (!bank_apply(&t->financial institution, entry)) {
        fprintf(stderr, "Out of reminiscence. The entry was saved; run this system once more to reload the ledger.n");
        bank_free(&t->financial institution);
        exit(EXIT_FAILURE);
    }
    return 1;
}

A save can fail for atypical causes: a full disk, a file locked by one other program, a USB stick pulled out. As a result of the write comes first, a failed save modifications nothing. Right here the ledger factors right into a folder that doesn’t exist:

Select an possibility (0-11): 1
Holder identify: Ana Lopez
Handle: 12 Harbour Street, Springfield
Account sort (1 = Financial savings, 2 = Present): 1
Opening deposit: 1500
Couldn't save: No such file or listing. Nothing was modified.

The file facet is ledger_append(). It opens the ledger in append mode, so current traces are by no means rewritten, and checks each step that may fail, together with fclose(), as a result of a full disk is typically reported solely when the buffer is lastly written:

/* Provides entry to the top of the ledger at path, as one line. When
 * write_header is 1 (the financial institution has no entries but) and the file is empty or
 * new, the header line goes first.
 *
 * The file is opened in "a" (append) mode, so current traces are by no means
 * rewritten: the worst a crash can do is minimize the latest line quick, and
 * the loader detects that (a final line with out 'n'). The entire textual content is
 * written with one fputs(), then fflush() and fclose() are each checked,
 * as a result of a full disk could solely be reported when the buffer is written
 * out. That's this program's model of an atomic write; an actual financial institution
 * would use a database transaction (for instance SQLite).
 * Returns 1 on success; in any other case places the strerror() textual content in error and
 * returns 0. */
int ledger_append(const char *path, const Entry *entry, int write_header, char *error, size_t error_size)
{
    char line[LEDGER_LINE], textual content[LEDGER_LINE + sizeof LEDGER_HEADER + 2];
    FILE *f;

    if (!entry_to_line(entry, line, sizeof line)) {
        snprintf(error, error_size, "the entry is simply too lengthy for one ledger line");
        return 0;
    }
    errno = 0;
    f = fopen(path, "a");
    if (f == NULL) {
        snprintf(error, error_size, "%s", strerror(errno));
        return 0;
    }
    /* Solely an empty file will get the header, so a failed first write that
     * left the header behind can not trigger a second header line. */
    if (write_header && fseek(f, 0, SEEK_END) == 0 && ftell(f) == 0)
        snprintf(textual content, sizeof textual content, "%snpercentsn", LEDGER_HEADER, line);
    else
        snprintf(textual content, sizeof textual content, "%sn", line);

    int okay = fputs(textual content, f) >= 0 && fflush(f) == 0 && !ferror(f);
    int err = errno;
    if (fclose(f) != 0 && okay) {
        okay = 0;
        err = errno;
    }
    if (!okay)
        snprintf(error, error_size, "%s", strerror(err != 0 ? err : EIO));
    return okay;
}

The worst a crash can do right here is minimize the latest line quick. A database resembling SQLite goes additional with atomic commit, the place both all modifications in a transaction occur or none do. For a single textual content file, one full line per entry plus a examine for a cut-short final line is the sensible equal. The fundamentals of opening, writing and checking information are in file dealing with in C.

Catching a Broken Ledger

A financial institution should not guess about cash. Many small packages skip a line they can not learn and stick with it; this one stops on the first drawback and names the file line, so the injury will be discovered and the file fastened or restored from a backup.

--verify masses and checks the ledger with out opening the menu. On the ledger from the pattern session:

OK: 3 account(s), 14 ledger entries, final entry 2026-12-01. Cash held: 6,467.38.

Now change one deposit by hand, turning 250.75 into 25,075.00 and fixing that line’s personal steadiness so it seems to be constant:

-4|2026-12-01|DEP|100001|25075|175075
+4|2026-12-01|DEP|100001|2507500|2657500

The edited line passes by itself, however the subsequent deposit to the identical account nonetheless says its steadiness is 1,850.75, and the replay says in any other case:

financial institution.txt line 6: the steadiness after must be 26,675.00, not 1,850.75

Each later line repeats the account’s steadiness, so a change in a single place disagrees with the traces after it. Curiosity makes this even stricter: the curiosity line should equal 3.00% / 12 of the steadiness at that second, so a cast steadiness additionally breaks the curiosity.

The opposite widespread injury is a line minimize quick when this system stopped mid-write. An entire line all the time ends with a newline, so a final line with out one is reported as a substitute of being half used:

/* Reads the following line of f into buf (measurement LEDGER_LINE) and removes its
 * line ending. A line should finish with 'n': with out one, both the road
 * didn't slot in buf (too lengthy) or the file ended in the course of a line
 * (this system stopped whereas writing it).
 * Returns 1 for an entire line, 0 on the finish of the file, or -1 with the
 * purpose in why. */
static int next_line(FILE *f, char *buf, char *why, size_t why_size)
{
    if (fgets(buf, LEDGER_LINE, f) == NULL)
        return 0;
    size_t len = strlen(buf);
    if (len == 0 || buf[len - 1] != 'n') {
        if (feof(f))
            snprintf(why, why_size, "the final line is incomplete (this system could have stopped whereas writing it)");
        else
            snprintf(why, why_size, "the road is simply too lengthy");
        return -1;
    }
    buf[--len] = '';
    if (len > 0 && buf[len - 1] == 'r')
        buf[--len] = '';                      /* a ledger copied from Home windows */
    return 1;
}

That is what the teller sees when the pc misplaced energy in the course of saving entry 14:

Financial institution Administration System
======================
At present is 2026-12-02.
financial institution.txt line 15: the final line is incomplete (this system could have stopped whereas writing it)
The ledger was not modified. Repair or restore it, then strive once more.

The repair is to delete the unfinished final line (the transaction was by no means confirmed on display screen) and begin once more. This system additionally refuses to begin when the pc’s date is sooner than the final entry, as a result of a unsuitable clock should not let anybody publish backdated transactions:

Financial institution Administration System
======================
At present is 2026-11-30.
At present (2026-11-30) is sooner than the final ledger entry (2026-12-01). Verify the date and check out once more.

These checks have limits, and they’re price understanding. They catch accidents, a torn write and informal edits; they don’t cease a decided one who rewrites each later line persistently. Additionally they can not inform that entire traces had been deleted from the top of the file, as a result of a shorter ledger remains to be a legitimate ledger. Defending in opposition to each wants a secret key, an concept lined within the extensions under.

Month-to-month Curiosity With out Rounding Errors

Financial savings accounts earn 3.00% a yr, paid month-to-month. With cash in cents and the speed in foundation factors (300 = 3.00%), the entire calculation stays in integers:

/* Returns one month's curiosity on steadiness at rate_bp foundation factors a yr
 * (300 = 3.00%), rounded half as much as the cent, utilizing integers solely.
 *
 * A yr's curiosity is steadiness * rate_bp / 10000, and a month is a twelfth
 * of that, so the divisor is 12 * 10000 = 120000. Integer division all the time
 * rounds down; including half the divisor (60000) first turns that into
 * "spherical half up": 4.626875 turns into 4.63 and precisely 0.005 turns into 0.01.
 *
 * The product can not overflow: MAX_BALANCE * 300 is about 3 * 10^13, and
 * an extended lengthy holds as much as about 9.2 * 10^18.
 * Returns 0 when the steadiness is zero or detrimental: no curiosity is charged
 * or paid on a debt by this perform. */
Cents interest_for_month(Cents steadiness, int rate_bp)
{
    if (steadiness <= 0)
        return 0;
    return (steadiness * rate_bp + 60000) / 120000;
}

These are the values from the pattern session, plus the rounding boundary:

Steadiness Precise month-to-month curiosity Posted
1,850.75 4.626875 4.63
4,600.50 11.50125 11.50
5,012.50 12.53125 12.53
2.00 0.005 0.01 (precisely half rounds up)
1.99 0.004975 0.00 (not posted)

Posting curiosity is idempotent: working it twice in the identical month pays nothing the second time, as a result of the ledger already reveals an INT line for that month and bank_check() refuses one other one. Within the pattern session the primary run posted 16.13 to 2 financial savings accounts, and the second run, a second later, modified nothing:

Select an possibility (0-11): 9
Curiosity for 2026-12 was already posted. Nothing was modified.

That additionally makes a failure partway by protected. If the disk fills up after 20 of fifty accounts, this system says so, and working the choice once more pays solely the 30 which can be lacking.

One simplification is price stating: curiosity is calculated on the steadiness for the time being it’s posted. Actual banks normally pay on the common every day steadiness over the month; that’s listed under as an extension.

Stories: Statements, Account Listing and Day by day Report

An announcement lists each entry that touched the account, with a working steadiness. A switch seems as “Switch to” on one assertion and “Switch from” on the opposite.

Select an possibility (0-11): 5
Account quantity: 100001

Account 100001 (Financial savings, open)
Holder:  Ana Lopez
Handle: 14 Harbour Street, Springfield
Opened:  2026-12-01

Date         No.  Description                     Debit       Credit score        Steadiness
2026-12-01     1  Opening deposit                           1,500.00       1,500.00
2026-12-01     4  Money deposit                                250.75       1,750.75
2026-12-01     5  Money deposit                                100.00       1,850.75
2026-12-01    12  Particulars up to date                                          1,850.75
2026-12-01    13  Curiosity for 2026-12                          4.63       1,855.38
Steadiness: 1,855.38

The account listing provides up the cash the financial institution holds. An overdrawn present account counts as detrimental:

Select an possibility (0-11): 6

Account Holder                         Kind    Standing         Steadiness
100001  Ana Lopez                      Financial savings open          1,855.38
100002  Ben Kim                        Present closed            0.00
100003  Carla Diaz                     Financial savings open          4,612.00
3 account(s): 2 open, 1 closed. Cash held: 6,467.38.

The every day report lists each transaction on a date, then the totals. Transfers transfer cash between two accounts of the identical financial institution, in order that they cancel out and are disregarded of the web change:

Select an possibility (0-11): 8
Date (YYYY-MM-DD, or Enter for right this moment): 

Transactions on 2026-12-01:
 No.  Account  Description                     Debit       Credit score
   1  100001   Opening deposit                           1,500.00
   2  100002   Opening deposit                           2,500.50
   3  100003   Opening deposit                           1,000.00
   4  100001   Money deposit                                250.75
   5  100001   Money deposit                                100.00
   6  100002   Money withdrawal              2,900.00
   7  100003   Money deposit                              9,000.00
   8  100003   Money withdrawal              4,000.00
   9  100003   Money withdrawal              1,000.00
  10  100003   Switch to 100002             399.50
  10  100002   Switch from 100003                        399.50
  11  100002   Account closed
  12  100001   Particulars up to date
  13  100001   Curiosity for 2026-12                          4.63
  14  100003   Curiosity for 2026-12                         11.50

Deposits:         6, whole 14,351.25
Withdrawals:      3, whole 7,900.00
Transfers:        1, whole 399.50
Curiosity paid:    2, whole 16.13
Web change in cash held: 6,467.38

The totals examine one another: deposits minus withdrawals plus curiosity (14,351.25 − 7,900.00 + 16.13) is strictly the 6,467.38 the account listing reveals.

Widespread Errors in Financial institution Administration Initiatives

These patterns flip up time and again in financial institution administration tasks shared on-line. Each is averted on this program, and the reason being within the code feedback.

  1. Cash in float or double. Rounding errors seem after a couple of transactions. Retailer entire cents in an integer sort.
  2. scanf("%s", identify) right into a small array. A protracted identify writes previous the top of the array. Learn entire traces with fgets() and examine the size.
  3. One file per buyer, named after the shopper. Two prospects with the identical identify overwrite one another, and a reputation containing path characters can write wherever. Give accounts numbers and hold the info in a single file.
  4. Rewriting the info file in place. A crash midway by the write loses the info. Append new traces, or write a brief file and rename it.
  5. Calling the menu perform once more to “return”. Every name provides to the decision stack and by no means returns. Use one loop in primary() that each possibility returns to.
  6. No checks on withdrawals. With no steadiness examine, an account can go detrimental with out restrict. Verify each rule earlier than something is saved.
  7. PINs and passwords in plain textual content. Anybody who opens the file can learn them. Hash them with a correct library, or go away login out.
  8. conio.h, graphics.h and system("cls"). These tie this system to at least one outdated compiler or one working system. Commonplace C runs in all places.

Concepts to Lengthen the Undertaking

This system is a strong base for a bigger mission. Every concept under matches into the prevailing modules.

  • Teller login with hashed PINs. Use libsodium’s high-level password hashing API (crypto_pwhash_*, which makes use of Argon2id), and retailer solely the hash, by no means the PIN.
  • Curiosity on the common every day steadiness. Replay the month’s entries daily and common the balances as a substitute of utilizing the steadiness on the posting day.
  • Month-to-month snapshots. Save each steadiness on the finish of every month, and replay solely the entries after the newest snapshot.
  • Assertion export to CSV, so a buyer’s historical past opens in a spreadsheet.
  • A tamper-evident chain. Add a hash of the earlier line to each line. Use an HMAC with a secret key, as a result of a plain hash will be recomputed by whoever edits the file. Retailer the final entry quantity and hash someplace else too, so a deleted tail is seen.
  • SQLite as a substitute of a textual content file, with one database transaction per teller motion.
  • File locking, so two copies of this system can not write to the identical ledger without delay.

Utilizing It as a School Undertaking

The mission works properly as a final-year or semester mission in a C course, so long as you perceive and may clarify each a part of it. Examiners normally ask questions like these, and every has a solution on this article and within the feedback of the code:

  • Why is cash saved as lengthy lengthy cents as a substitute of float?
  • What occurs if the ability fails whereas this system is saving?
  • How does this system cease a withdrawal that might break the overdraft restrict, even when somebody edits the info file?
  • Why is this system break up into seven information, and what does every one do?

For a mission report, the module desk, Determine 1, the foundations desk and the take a look at leads to What I Verified are ready-made materials. Add one extension from the listing above and you’ve got work of your individual to current. Credit score the supply of any code you reuse; the repository’s MIT license permits reuse with that discover stored.

Key Takeaways

  • Cash belongs in integers. Storing entire cents in a lengthy lengthy makes each sum precise; a double turns ten deposits of 0.10 into 0.99999999999999989.
  • A ledger is safer than a steadiness. Recording what occurred, and rebuilding balances from it, retains a full historical past and makes each quantity explainable.
  • One rule perform for each path means a hand-edited file can not sneak in a transaction the menu would refuse.
  • Write to the file first, then change reminiscence, so a failed save by no means reveals cash that doesn’t exist.
  • Fail closed on broken knowledge. Stopping on the first unhealthy line, with its line quantity, is healthier than guessing about cash.
  • Integer curiosity with half-up rounding offers the identical cent on each compiler and each run.
  • Splitting this system into modules is what makes it testable: the unit exams name the foundations instantly, with out the menu.

Conclusion

A financial institution administration system is a traditional C mission as a result of it touches all the things an actual program wants: structured knowledge, information, enter that can’t be trusted and guidelines that must not ever be damaged. The alternatives that matter most usually are not the menu or the display screen structure. They’re storing cash as integers, retaining a historical past as a substitute of a steadiness, checking each change with one algorithm, and refusing to guess when the info seems to be unsuitable.

These habits carry over to any program that retains information, from stock to payroll. Begin with the code as it’s, run the exams, then choose one extension and make it your individual. Extra tasks and tutorials are within the C programming part.

Supply Code and Exams

Bank management system build status

All of the code on this web page is within the tasks/bank-management listing of the MYCPLUS C examples repository, beneath the MIT license.

Construct and take a look at (CMake 3.16 or later; on Home windows, use a Developer Command Immediate):

cmake -S . -B construct
cmake --build construct
ctest --test-dir construct --output-on-failure

What the construct checks. Each push compiles this system with GCC and Clang beneath C11 and C17 with -Wall -Wextra -pedantic -Werror, and with MSVC beneath /W4 /WX, so a single warning fails the construct. Then 27 exams run in every configuration:

  • Unit exams: 2,145 checks of money_parse, money_format, curiosity rounding, dates, each rule bank_check() can return, and a spherical journey of each entry sort by the file format.
  • A full session: the teller session from this text, in contrast character by character with the anticipated output, then --verify on the ledger it wrote.
  • Persistence: three runs on one ledger over totally different dates, together with the refusal to begin with an earlier date.
  • Finish of enter, a nasty command line, a lacking file, and a holder identify typed with a management character in it.
  • 17 broken ledgers: every have to be rejected with exit code 2 and the precise line quantity and purpose.

The identical exams run once more beneath AddressSanitizer and UndefinedBehaviorSanitizer. The exams don’t cowl concurrent use by two packages without delay, which this system doesn’t help.

What I Verified

Verify Ubuntu 24.04 Home windows (MSVC)
Construct with zero warnings, C11 and C17 GCC 13.3 and Clang 18.1, -Wall -Wextra -pedantic -Werror /W4 /WX, in GitHub Actions and on a Home windows PC
One-line construct instructions from this text gcc -std=c11 -Wall -Wextra builds with no warnings cl /W4 builds with no warnings
27 CTest instances All cross (GitHub Actions, Ubuntu 24.04 runner) All cross (GitHub Actions)
Unit exams 2,145 checks, 0 failed 2,145 checks, 0 failed
AddressSanitizer and UndefinedBehaviorSanitizer, each take a look at Clear, no leaks Not relevant
400 random multi-day teller periods (7,550 ledger traces, earlier than the ultimate name-check repair) No crash or sanitizer report; each ledger replayed by a separate Python mannequin offers the identical accounts and cash held Not run
2,000 randomly broken ledgers (earlier than the ultimate name-check repair) No crash; each change that alters a steadiness is rejected, besides a file minimize off precisely at a line finish (see “Catching a Broken Ledger”) Not run
Load time of a 100,011-entry ledger (-O2, 2-CPU container, 3 runs) 30 to 35 ms, similar totals because the Python mannequin Not run
Curiosity and rounding values on this article Computed independently in Python, match this system Identical exams cross

Not lined: macOS, 32-bit builds, and two copies of this system writing to at least one ledger on the similar time.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments