Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 135 ยท Projects

Project: Inventory with a Linked List

Build an inventory manager in C in four stages - a sorted linked list of items, a command interpreter, a portable binary file format, and save and load commands.

Every shop, warehouse and workshop keeps an inventory: a list of items, how many of each are in stock, and what they cost. It's also a classic C project, because it needs almost every skill a C programmer uses daily: structs that own their data, a linked data structure built with pointers, a command interpreter that refuses bad input, error codes that say exactly what went wrong, and a file format that survives being saved on one machine and loaded on another.

You'll build a small stationery shop's inventory in four stages. Stage 1 is the core: a sorted linked list of items with add, find and remove. Stage 2 drives the list with commands from the Input box. Stage 3 designs a binary file format and saves and loads it safely. Stage 4 joins everything into a complete program with sell, restock, low-stock and save/load commands. Each stage is a complete program, because every run starts fresh; files written during a run disappear when it ends, so the save and load stages write and read the file in the same run.

The project uses structures and pointers, linked lists, pointers to pointers, dynamic memory, string functions including strtok, string conversions, function pointers, binary files and error handling.

Stage 1: a sorted linked list of items

The item. Each item has a stock-keeping unit code (SKU) such as PEN-BLK, a name, a quantity and a price. Two design decisions hide in that sentence:

  • Prices are integers in cents. A price like 1.20 can't be stored exactly in a double (see Floating-Point Numbers), and summing thousands of slightly wrong values gives totals that are off by a cent. Money in programs is almost always stored as an integer count of the smallest unit. long long holds any realistic total.
  • Strings live inside the struct as fixed-size arrays: char sku[16] and char name[32]. That limits their length, but it means an item is one allocation, freeing it is one free, and the struct can later be written to a file as fixed-size fields. The alternative, char *name pointing to a separate allocation, allows any length but doubles the bookkeeping.

Why a linked list? The inventory changes constantly: items are added and removed in the middle, in SKU order. In a linked list, inserting or removing an item only rewires a pointer or two, and no other item moves, so a pointer to an item stays valid while others come and go. The price is that finding an item means walking the list from the start, which is fine for the hundreds of items a small shop has (a hash table or a binary search tree would scale further).

Pointer-to-pointer insertion and removal. The classic way to insert into a sorted list needs a special case for the head: inserting before the first node changes head, inserting anywhere else changes some node's next. The program avoids that with a single item **link that points at "the pointer that will have to change", whether that's inv->head or some node's next field. The loop walks link forward until it points at the place where the new item belongs, then does new_item->next = *link; *link = new_item;. Removal uses the same idea: *link = gone->next unlinks the item, whether it was first or not. This technique is explained step by step in Pointers to Pointers.

Status codes instead of printing. The list functions never print. They return an inv_status enumeration (INV_OK, INV_DUPLICATE, INV_NOT_FOUND, โ€ฆ), and inv_message turns a status into text. The caller decides what to say and whether to continue. Keeping the data structure silent is what makes it reusable: the same functions will work unchanged under the command interpreter in stage 2.

C Stage 1: a sorted linked list of items

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 items were added in no particular order, but the report lists them by SKU (CLIP-25, NB-A5, PEN-BLK, TAPE-19), because every insertion puts the item in its sorted place. The second NB-A5 is rejected as a duplicate, and so is the second removal of TAPE-19, each with a clear message. The prices print as 1.20 and 6.50 from integer cents, with %02lld supplying the leading zero of the cents.

Two small details carry a lot of weight:

  • inventory_find returns a pointer into the list, so the caller can change the item in place (pen->quantity -= 30). The pointer stays valid until that item is removed; removing other items doesn't affect it. That's a guarantee a resizable array can't give, since realloc may move every element.
  • inventory_free reads next before calling free. Reading it->next after free(it) is a use-after-free, one of the memory errors that often "works" in testing and then fails in production.

Stage 2: a command interpreter

A real inventory tool takes commands. Stage 2 reads one command per line from the Input box, with this small language:

TEXT
add SKU QUANTITY PRICE NAME...   add an item, for example: add PEN-BLK 250 1.20 Black gel pen
remove SKU                       remove an item
find TEXT                        list items whose name contains TEXT (any case)
report                           print every item and the total stock value
quit                             stop reading commands

Blank lines and lines starting with # are ignored, which makes the Input box easy to annotate.

Splitting a line into words. strtok from <string.h> splits a string at delimiters by writing '\0' over them and returning one token per call: the first call takes the string, later calls take NULL to continue where the last one stopped. The name may contain spaces, so after reading the SKU, quantity and price, the program calls strtok(NULL, ""). An empty delimiter set means "give me everything that's left". Because strtok modifies the line, the program prints the line (as an echo) before tokenizing it. And because strtok keeps its position in a hidden static variable, it isn't safe to use in two places at once (POSIX offers strtok_r for that).

Validating every field. Each argument gets its own parser that returns false on bad input, so main can report exactly which field was wrong:

  • SKU: 1 to 15 characters, only letters, digits and dashes. parse_sku also converts letters to uppercase, so pen-blk and PEN-BLK are the same item. Normalizing input once, at the edge of the program, keeps the rest of the code simple.
  • Quantity: must start with a digit (so -5 and +5 are rejected), parsed with strtol and an end pointer, and at most MAX_QUANTITY. The constant is written 1'000'000, using the C23 digit separator; older compilers need 1000000.
  • Price: parsed without floating point. parse_money reads the whole units with strtoll, then an optional dot followed by one or two digits, and builds the cents directly. 1.2, 1.20 and 12 are accepted; 1.234, 1,20 and abc are not.
  • Name: must not be empty and must fit in NAME_SIZE - 1 characters. Rejecting a long name is friendlier than silently truncating it.

Case-insensitive search. Standard C has no case-insensitive substring search (strcasestr is a GNU extension), so contains_ignore_case compares character by character with tolower. It's a simple quadratic loop, perfectly fine for short names.

C Stage 2: commands from the Input box

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.

Read the transcript against the Input box. pen-blk was stored as PEN-BLK. The duplicate notebook, the quantity x and the price 0.9.0 each failed with a message that names the problem, and the inventory was left unchanged. find PEN matched "Black gel pen" regardless of case. The first remove tape-19 worked, the second reported that the item no longer exists, fly away was an unknown command, and nothing after quit ran, so the final report line in the Input box was never executed.

The echo prints only the command word (> add), because by the time the program knows the line isn't a comment, strtok has already cut the line after the first word. If you'd like the full line echoed, copy it into a second buffer before tokenizing.

The stock value is price_cents * quantity, summed in a long long. With MAX_QUANTITY of one million and prices up to one million units (100 million cents), one item's value can reach 1014 cents, far beyond int but comfortably inside the range of long long (at least 9.2 ร— 1018). Choosing the limits and the types together is how you rule out overflow instead of hoping for the best (see Type Limits).

Stage 3: a binary file format

An inventory that vanishes when the program ends isn't much use. Stage 3 adds inventory_save and inventory_load, and the most important work happens before any code: designing the file format.

The tempting shortcut is fwrite(it, sizeof *it, 1, file), writing each struct exactly as it sits in memory. It has three problems, all covered in Binary Files:

  • The struct contains the next pointer, which is meaningless in a file: the address won't be valid in the next run.
  • The compiler may insert padding between members, and its amount depends on the compiler and the platform (see Padding and Alignment).
  • Integers are stored in the machine's byte order and size. A file written on a little-endian PC would read as nonsense on a big-endian machine.

So the program writes every field explicitly, in a fixed, documented layout:

TEXT
offset  size  content
0       4     magic bytes "INV1" (identifies the file type and version)
4       4     number of records, unsigned, little-endian
8       60    record 1: sku (16 bytes), name (32 bytes),
              quantity (4 bytes, little-endian), price in cents (8 bytes, little-endian)
68      60    record 2 ...

put_u32 and put_u64 write integers one byte at a time, lowest byte first, using shifts and masks (bitwise operators); get_u32 and get_u64 reassemble them. Because the code decides the byte order instead of the CPU, the file is identical on every machine. The magic bytes let inventory_load reject a file that isn't an inventory at all, and the 1 in INV1 leaves room for a future format version.

Never trust a file. A file can be truncated, corrupted or simply be something else. inventory_load checks every fread, forces the strings to be null-terminated (a corrupted name without a '\0' would otherwise make printf read past the array), and checks the quantity and price against the same limits as the command parser. It also loads into a new, temporary inventory, and replaces the caller's inventory only after the whole file has been read successfully. If anything goes wrong, the old inventory is untouched: loading either fully succeeds or changes nothing.

Cleanup with goto. inventory_load has many ways to fail after opening the file, and each must close it and free the half-built list. Instead of repeating that cleanup at every failure, each check jumps to one done: label. This is the one widely accepted use of goto in C (see break, continue and goto).

Why calloc in inventory_add. snprintf fills a name like "Black gel pen" and its '\0', but leaves the remaining bytes of the 32-byte array untouched. With malloc, those bytes would contain leftovers from earlier allocations, and inventory_save would copy them into the file. That makes the output change from run to run, and in a real program it can leak sensitive data from memory into files. calloc zeroes the struct, so unused bytes are always 0.

C Stage 3: saving and loading a binary file

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 file is 188 bytes: an 8-byte header plus three 60-byte records, exactly as designed. The hex dump shows the format directly. The first four bytes, 49 4E 56 31, are the ASCII codes of INV1; the next four, 03 00 00 00, are the count 3 with the lowest byte first. Then the first record begins with CLIP-25 (43 4C 49 50 2D 32 35), followed by the zero bytes that calloc put in the unused part of the SKU field.

Loading stock.inv replaced the placeholder item OLD-1 with the three saved items. Loading a text file failed the magic check, loading a missing file failed at fopen, and in both cases the inventory still holds its 3 items.

inventory_save checks the result of fclose. The C library buffers output, so many bytes are actually written to the disk during fclose, not during fwrite. A full disk may only be reported there. Ignoring fclose's return value on an output file is a classic way to lose data silently.

Stage 4: the complete inventory manager

The final program combines the list, the command interpreter and the file format, and adds a few commands a shop would need:

TEXT
add SKU QUANTITY PRICE NAME...   add an item
remove SKU                       remove an item
sell SKU N                       take N units out of stock (not more than there are)
restock SKU N                    add N units
find TEXT                        search names, any case
low LIMIT                        list items with fewer than LIMIT units
report                           print every item and the totals
save FILE / load FILE            write or read a binary inventory file
help                             list the commands
quit                             stop

With ten commands, the if/else if chain from stage 2 would get long. Stage 4 replaces it with a dispatch table: an array of structs, each holding a command's name, its usage text and a pointer to the function that runs it. main looks the command up in the table and calls the function through the pointer. Adding a command now means writing one function and adding one line to the table, and the help command simply prints the table, so it can never be out of date. All handlers have the same signature, void handler(inventory *inv), which is what lets them share one function pointer type (see Function Pointers).

Error messages for files. When fopen fails, it sets errno, and strerror(errno) turns it into text such as "No such file or directory". The load and save handlers save errno into a local variable right after the call, before anything else (like printf) gets a chance to overwrite it (see Error Handling).

Saving safely. A program that writes directly to stock.inv and fails halfway, because the disk filled up, has destroyed the previous good file. command_save writes to a temporary file first (stock.inv.tmp) and only renames it over the real name after the save fully succeeded. On POSIX systems, rename replaces the target in one step, so the file on disk is always either the complete old version or the complete new one. (On Windows, rename fails if the target exists, so portable code removes the target first or uses a platform API.)

C Stage 4: the complete inventory manager

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.

Follow the transcript. Selling 30 pens leaves 220; trying to sell 5 paper clips when only 3 exist sells nothing, and the restock brings them to 23. After save stock.inv, two items are removed and the report shows only two items left. Then load stock.inv brings back all four, exactly as they were at the moment of saving, and low 25 finds the paper clips. Loading a file that doesn't exist reports the operating system's reason, and the inventory is unchanged, as the last report confirms.

A few details in the final program:

  • The full line is echoed now, because main prints it before strtok runs. Stage 2 showed why the order matters.
  • command_restock checks before adding: amount > MAX_QUANTITY - it->quantity can't overflow, while it->quantity + amount > MAX_QUANTITY could, for large values. Testing the limit by rearranging the inequality is the standard way to prevent signed overflow (see Undefined Behavior).
  • command_help is declared before the table and defined after it, because the table refers to the function and the function prints the table. A forward declaration (prototypes) breaks the cycle.
  • (void)inv; tells the compiler (and the reader) that ignoring the parameter is intentional, which silences the unused-parameter warning from -Wextra.

Ideas to extend it

  • An append-only transaction log. Write every sell and restock to a text file with the time from time() (see Time and Date), so stock changes can be audited.
  • Faster loading. inventory_add walks the list to find each item's place, so loading n items takes about nยฒ/2 steps. Since the file is already sorted, add an "append" function that keeps a tail pointer.
  • A price-sorted report. Copy the item pointers into an array and sort it with qsort by stock value, without touching the list's SKU order.
  • Format version 2. Add a "minimum stock" field per item. Make load accept both INV1 and INV2 files, and always save INV2.
  • A hash index. Keep the linked list for ordered reports, and add a hash table from SKU to item * for constant-time lookups.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the program store prices as long long cents instead of double?

    Most decimal fractions are rounded when stored as double, and the errors add up over many operations. Counting cents in an integer type keeps every amount exact.
  2. 2. In inventory_add, link is an item **. Where does it point when the new item belongs at the very front of the list?

    The loop starts with link = &inv->head and stops immediately if the new SKU sorts first. Assigning through *link then changes inv->head, so the head needs no special case.
  3. 3. Why doesn't the program save each item with fwrite(it, sizeof *it, 1, file)?

    Writing raw structs saves the next pointer and any padding bytes, and the layout differs between platforms. Writing each field in a documented little-endian format makes the file portable.
  4. 4. inventory_load finds a truncated record halfway through the file. What happens to the inventory passed in?

    Loading into a separate list and swapping it in only after success makes load all-or-nothing. On failure, the temporary list is freed and the caller's inventory is untouched.
  5. 5. Why does command_save write to stock.inv.tmp and then rename it?

    If the program wrote directly to stock.inv and the disk filled up, both the old and the new data would be lost. Writing a temporary file first and renaming it on success keeps a complete file on disk at all times.

Summary

  • Keep money in integer cents, choose limits for every field, and pick types that can hold the largest possible totals.
  • A sorted singly linked list gives cheap inserts and removals and stable item pointers; an item **link that points at "the pointer to change" removes every special case for the head.
  • Let data-structure functions return status codes instead of printing; the caller decides how to report problems.
  • Parse commands with fgets and strtok (and strtok(NULL, "") for the rest of the line); validate and normalize each field at the edge of the program.
  • A dispatch table of names and function pointers keeps a command interpreter short, extensible and self-documenting.
  • Design binary formats explicitly: magic bytes, a count, fixed-size fields, and integers written byte by byte in a chosen byte order. Use calloc so unused bytes are zero.
  • Never trust a file: check every read, force strings to be terminated, validate values, load into a temporary structure, and clean up through one goto label.
  • Check fclose on output files, save errno right after a failing call, and write to a temporary file before renaming it over the real one.

Next: C Cheat Sheet, a dense one-page reference to everything in this course, from types and format specifiers to pointers, memory, files and the standard headers.