In this project you will build the core of a shop’s stock system. It saves products to a binary file and loads them back. It updates stock levels directly on disk and refuses sales that would make stock negative. It flags items that need reordering and prints a sorted stock-value report. The program uses many tools from this part of the C series: fixed-width integers, printf formatting, binary files with fseek, qsort and careful error checking.
In this project you will
- Design a record and a file header with a “magic number”
- Store money safely as whole numbers of poisha
- Save and load all records, checking every step
- Update one record in place with random access
- Sort and print a formatted report
You should know binary files and fseek, fixed-width integers, printf formatting and qsort.
The Design
The file starts with a small header, followed by the item records, all the same size:
+----------------------+--------+--------+--------+-----+
| Header: magic, count | Item 0 | Item 1 | Item 2 | ... |
+----------------------+--------+--------+--------+-----+
8 bytes 40 bytes each
Item k starts at byte sizeof(Header) + k * sizeof(Item)
- The magic number 0x494E5631 (the letters “INV1”) marks the file as ours. If someone opens the wrong file, the program notices instead of reading garbage.
- Prices are stored in poisha (1 taka = 100 poisha) as whole numbers.
floatanddoublecannot store most decimal amounts exactly, so whole numbers keep money calculations exact. - Every field has a fixed size:
uint32_t,int32_tand a 24-byte name. Quantity is signed so a mistake that would go below zero can be detected.
The Complete Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
#define DB_FILE "inventory.dat"
#define MAGIC 0x494E5631u /* "INV1": identifies our file format */
#define NAME_LEN 24
typedef struct {
uint32_t id;
char name[NAME_LEN];
int32_t qty;
uint32_t price; /* price in poisha (1 taka = 100 poisha) */
int32_t reorder_level;
} Item;
typedef struct { uint32_t magic; uint32_t count; } Header;
/* ---------- file storage ---------- */
static int save_all(const Item *items, uint32_t n) {
FILE *f = fopen(DB_FILE, "wb");
if (!f) { perror("save"); return -1; }
Header h = {MAGIC, n};
int ok = fwrite(&h, sizeof h, 1, f) == 1 && fwrite(items, sizeof *items, n, f) == n;
fclose(f);
return ok ? 0 : -1;
}
static Item *load_all(uint32_t *n) {
FILE *f = fopen(DB_FILE, "rb");
if (!f) return NULL;
Header h;
if (fread(&h, sizeof h, 1, f) != 1 || h.magic != MAGIC) {
fprintf(stderr, "not an inventory file\n");
fclose(f);
return NULL;
}
Item *items = malloc(h.count * sizeof *items);
if (items && fread(items, sizeof *items, h.count, f) != h.count) {
free(items);
items = NULL;
}
fclose(f);
*n = items ? h.count : 0;
return items;
}
/* Change one item's quantity directly in the file, without loading the rest */
static int adjust_stock(uint32_t index, int32_t change) {
FILE *f = fopen(DB_FILE, "r+b");
if (!f) return -1;
long pos = (long)sizeof(Header) + (long)index * (long)sizeof(Item);
Item it;
int rc = -1;
if (fseek(f, pos, SEEK_SET) == 0 && fread(&it, sizeof it, 1, f) == 1) {
if (it.qty + change < 0) {
printf(" refused: only %" PRId32 " %s in stock\n", it.qty, it.name);
} else {
it.qty += change;
fseek(f, pos, SEEK_SET);
rc = fwrite(&it, sizeof it, 1, f) == 1 ? 0 : -1;
printf(" %s: %+" PRId32 " -> %" PRId32 " left\n", it.name, change, it.qty);
}
}
fclose(f);
return rc;
}
/* ---------- reports ---------- */
static int by_value_desc(const void *a, const void *b) {
const Item *x = a, *y = b;
uint64_t vx = (uint64_t)x->qty * x->price, vy = (uint64_t)y->qty * y->price;
return (vx < vy) - (vx > vy);
}
static void print_table(const Item *items, uint32_t n) {
printf("%-4s %-18s %5s %10s %12s\n", "ID", "Name", "Qty", "Price", "Value");
uint64_t total = 0;
for (uint32_t i = 0; i < n; i++) {
uint64_t value = (uint64_t)items[i].qty * items[i].price;
total += value;
printf("%-4" PRIu32 " %-18s %5" PRId32 " %7" PRIu32 ".%02" PRIu32 " %9" PRIu64 ".%02" PRIu64 "%s\n",
items[i].id, items[i].name, items[i].qty,
items[i].price / 100, items[i].price % 100,
value / 100, value % 100,
items[i].qty <= items[i].reorder_level ? " << reorder" : "");
}
printf("%-40s %9" PRIu64 ".%02" PRIu64 "\n", "Total stock value", total / 100, total % 100);
}
int main(void) {
Item start[] = {
{1, "Rice 25kg", 40, 185000, 10},
{2, "Lentils 1kg", 90, 13500, 30},
{3, "Soybean oil 5L", 12, 92000, 15},
{4, "Sugar 1kg", 55, 12500, 20},
{5, "Tea 400g", 8, 24000, 10},
};
if (save_all(start, 5) != 0) return 1;
uint32_t n;
Item *items = load_all(&n);
if (!items) return 1;
printf("Loaded %" PRIu32 " items from %s (%ld bytes)\n\n", n, DB_FILE,
(long)(sizeof(Header) + n * sizeof(Item)));
print_table(items, n);
free(items);
printf("\nStock movements:\n");
adjust_stock(0, -15); /* sold 15 bags of rice */
adjust_stock(2, +20); /* oil delivery arrived */
adjust_stock(4, -10); /* tries to sell more tea than we have */
adjust_stock(1, -65);
items = load_all(&n);
if (!items) return 1;
qsort(items, n, sizeof *items, by_value_desc);
printf("\nAfter movements, sorted by stock value:\n");
print_table(items, n);
free(items);
remove(DB_FILE);
return 0;
}
Output
Loaded 5 items from inventory.dat (208 bytes)
ID Name Qty Price Value
1 Rice 25kg 40 1850.00 74000.00
2 Lentils 1kg 90 135.00 12150.00
3 Soybean oil 5L 12 920.00 11040.00 << reorder
4 Sugar 1kg 55 125.00 6875.00
5 Tea 400g 8 240.00 1920.00 << reorder
Total stock value 105985.00
Stock movements:
Rice 25kg: -15 -> 25 left
Soybean oil 5L: +20 -> 32 left
refused: only 8 Tea 400g in stock
Lentils 1kg: -65 -> 25 left
After movements, sorted by stock value:
ID Name Qty Price Value
1 Rice 25kg 25 1850.00 46250.00
3 Soybean oil 5L 32 920.00 29440.00
4 Sugar 1kg 55 125.00 6875.00
2 Lentils 1kg 25 135.00 3375.00 << reorder
5 Tea 400g 8 240.00 1920.00 << reorder
Total stock value 87860.00
How It Works
- Saving:
save_allwrites the header and then every item, and returns −1 unless bothfwritecalls wrote everything. - Loading:
load_allreads the header, checks the magic number, allocates exactly enough memory forcountitems and reads them. Any failure frees the memory and returnsNULL, so the caller never gets half-loaded data. - Random access:
adjust_stockworks out the item’s byte position, reads only that item, changes the quantity and writes it back to the same place. With thousands of products, a sale still touches only 40 bytes on disk. - Business rule: the shop had only 8 packets of tea, so selling 10 was refused and the file was left unchanged.
- Money: 1850.00 taka is stored as 185,000 poisha. Printing uses
price / 100for taka andprice % 100for poisha, with%02so 5 poisha prints as “05”. Stock values are multiplied inuint64_t, so even large stocks cannot overflow. - Reorder flag: any item at or below its reorder level gets “<< reorder”. After selling 65 packets, lentils dropped to 25 and joined the list, while the oil delivery took oil off it.
- Sorting:
by_value_desccompares stock values with(vx < vy) - (vx > vy). This gives a descending order without subtracting large unsigned numbers, which could wrap around. - Formatting: the
PRIu32,PRId32andPRIu64macros print each fixed-width type correctly on any system, and fixed widths keep the columns lined up.
Ideas to Extend the Project
- Add a simple menu that reads commands with
fgets: list, add, sell, restock, report. - Look items up by ID with binary search after sorting by ID.
- Write each field in a fixed byte order so the file can be read on any computer.
- Keep a log file of every stock movement with the date from
<time.h>. - Find the five lowest-stock items with a heap.
Common Mistakes
- Storing money as
float, which turns 0.10 + 0.20 into 0.30000001. - Trusting the file’s
countblindly. A damaged file could claim billions of items; real programs also compare the count with the file size. - Multiplying quantity and price in 32 bits, which can overflow for expensive stock.
- Forgetting to
freethe array fromload_allbefore loading again.
Practice Exercises
Exercise 1. At which byte does item 3 (Sugar) start in the file?
Show answer
sizeof(Header) + 3 × sizeof(Item) = 8 + 3 × 40 = 128.
Exercise 2. Write a comparison function for qsort that sorts items by name, A to Z.
Show answer
static int by_name(const void *a, const void *b) {
const Item *x = a, *y = b;
return strcmp(x->name, y->name);
}
/* qsort(items, n, sizeof *items, by_name); */
Frequently Asked Questions
Why not just use a text file such as CSV?
Text files are easy to read and share, and are a good choice for exporting reports. But records in a text file have different lengths, so you cannot jump straight to item 5000 or update one item in place. Fixed-size binary records make that possible.
When should a program like this move to a real database?
When several people use it at once, when you need searches on many fields, or when losing data during a power cut is unacceptable. SQLite is a small C library that gives you all of that in a single file.
Summary
- A header with a magic number and count makes a binary file self-checking.
- Fixed-size records allow loading everything or updating one item in place.
- Store money as whole numbers of the smallest unit, and multiply in 64 bits.
- Check every file operation and free every allocation.
Back to the start of the series: C Programming Language Tutorial.
