Skip to content
KALANBLON
Show contents

Chapter 5 of 6 · 30 min

Project: a saved and tested inventory

By the end of this chapter, you'll be able to

  • Design a module's interface around a structure and functions that return an error code
  • Save and reload structures in a text file
  • Write tests with a checking macro that shows the faulty line
  • Explain why you never put a side effect in an assert

Step 1: the interface

The inventory is a structure that contains an array of items and their number. Every operation goes through functions prefixed inventory_, which return 0 on success and -1 on failure:

/* inventory.h */
#ifndef INVENTORY_H
#define INVENTORY_H

#define MAX_ITEMS 16

typedef struct {
    char name[32];
    int quantity;
    double price;
} Item;

typedef struct {
    Item items[MAX_ITEMS];
    int count;
} Inventory;

int inventory_add(Inventory *inv, const char *name, int quantity, double price);
int inventory_sell(Inventory *inv, const char *name, int quantity);
double inventory_value(const Inventory *inv);
int inventory_save(const Inventory *inv, const char *path);
int inventory_load(Inventory *inv, const char *path);

#endif

The file format is simple and readable: one line per item, name;quantity;price. The semicolon allows names with spaces.

On the next run, each line is read back and validated before being added.

Step 6 of 6
Text description of the animation
  1. An item is added after validation: positive quantity and price, name not too long.
  2. Adding an item that's already there increases its quantity instead of creating a duplicate.
  3. A sale larger than the stock is refused: the function returns -1 and changes nothing.
  4. Each item becomes a line of text.
  5. fclose guarantees everything is written to disk.
  6. On the next run, each line is read back and validated before being added.

Step 2: the program and its tests

Here, everything is gathered in a single file so it can be run. In your project, split it into inventory.h, inventory.c and test_inventory.c, with a Makefile.

#include <stdio.h>
#include <string.h>

#define MAX_ITEMS 16

/* Stops the test, showing the line and the condition that failed. */
#define CHECK(condition)                                                 \
    do {                                                                 \
        if (!(condition)) {                                              \
            printf("FAILED line %d: %s\n", __LINE__, #condition);       \
            return 1;                                                    \
        }                                                                \
    } while (0)

typedef struct {
    char name[32];
    int quantity;
    double price;
} Item;

typedef struct {
    Item items[MAX_ITEMS];
    int count;
} Inventory;

int inventory_add(Inventory *inv, const char *name, int quantity, double price) {
    if (quantity < 0 || price < 0 || strlen(name) >= sizeof inv->items[0].name) return -1;
    for (int i = 0; i < inv->count; i++) {
        if (strcmp(inv->items[i].name, name) == 0) {
            inv->items[i].quantity += quantity;
            return 0;
        }
    }
    if (inv->count == MAX_ITEMS) return -1;
    Item *it = &inv->items[inv->count++];
    strcpy(it->name, name);
    it->quantity = quantity;
    it->price = price;
    return 0;
}

int inventory_sell(Inventory *inv, const char *name, int quantity) {
    for (int i = 0; i < inv->count; i++) {
        if (strcmp(inv->items[i].name, name) == 0) {
            if (quantity <= 0 || quantity > inv->items[i].quantity) return -1;
            inv->items[i].quantity -= quantity;
            return 0;
        }
    }
    return -1;
}

double inventory_value(const Inventory *inv) {
    double total = 0;
    for (int i = 0; i < inv->count; i++) {
        total += inv->items[i].quantity * inv->items[i].price;
    }
    return total;
}

int inventory_save(const Inventory *inv, const char *path) {
    FILE *f = fopen(path, "w");
    if (f == NULL) return -1;
    for (int i = 0; i < inv->count; i++) {
        const Item *it = &inv->items[i];
        fprintf(f, "%s;%d;%.2f\n", it->name, it->quantity, it->price);
    }
    return fclose(f) == 0 ? 0 : -1;
}

int inventory_load(Inventory *inv, const char *path) {
    FILE *f = fopen(path, "r");
    if (f == NULL) return -1;
    inv->count = 0;
    char line[96];
    while (fgets(line, sizeof line, f) != NULL) {
        char name[32];
        int quantity;
        double price;
        if (sscanf(line, "%31[^;];%d;%lf", name, &quantity, &price) == 3) {
            inventory_add(inv, name, quantity, price);
        }
    }
    fclose(f);
    return 0;
}

int main(void) {
    Inventory inv = {.count = 0};
    CHECK(inventory_add(&inv, "Rice bag 5 kg", 12, 6.50) == 0);
    CHECK(inventory_add(&inv, "Oil 1 L", 20, 2.25) == 0);
    CHECK(inventory_add(&inv, "Rice bag 5 kg", 3, 6.50) == 0);    /* merged */
    CHECK(inventory_add(&inv, "Sugar", -4, 1.0) == -1);           /* refused */
    CHECK(inventory_sell(&inv, "Oil 1 L", 5) == 0);
    CHECK(inventory_sell(&inv, "Oil 1 L", 100) == -1);            /* not enough stock */
    CHECK(inventory_sell(&inv, "Coffee", 1) == -1);               /* unknown */
    CHECK(inv.count == 2);

    printf("%d items, value %.2f\n", inv.count, inventory_value(&inv));
    CHECK(inventory_save(&inv, "inventory.txt") == 0);

    Inventory reloaded = {.count = 0};
    CHECK(inventory_load(&reloaded, "inventory.txt") == 0);
    CHECK(reloaded.count == 2 && reloaded.items[1].quantity == 15);
    for (int i = 0; i < reloaded.count; i++) {
        printf("%-16s %3d x %5.2f\n", reloaded.items[i].name, reloaded.items[i].quantity, reloaded.items[i].price);
    }
    remove("inventory.txt");
    return 0;
}
2 items, value 131.25
Rice bag 5 kg     15 x  6.50
Oil 1 L           15 x  2.25

The choices worth noticing:

  • Validate before changing. inventory_sell checks the quantity before touching the stock: a refused sale leaves no trace.
  • No overflow. strlen(name) >= sizeof inv->items[0].name refuses a name that's too long before the strcpy, and %31[^;] limits reading to 31 characters. %[^;] reads every character except the semicolon: a name can contain spaces.
  • fclose checked. It's at fclose that the buffer is written to disk: a full disk often only shows up at that moment.
  • The CHECK macro displays the line (__LINE__) and the text of the condition (#condition) that failed, then stops the program with an error code. do { … } while (0) lets you use the macro as a statement, followed by a semicolon, with no surprises inside an if.

Your turn

Worked exercise

Worked exercise: the items to reorder

Add a function int inventory_to_reorder(const Inventory *inv, int threshold, char names[][32], int max) that copies into names the names of the items whose quantity is less than or equal to the threshold, at most max names, and returns their number. Test it: with items at 3, 15 and 0 units and a threshold of 5, it returns 2 and lists the two right names.

Hint 1
Go through the items, and for each one that meets the threshold, copy its name into names[n] with strcpy, then increase n.
Hint 2
Stop copying when n == max, so you never write beyond the array the caller provided.
Show the solution and common mistakes
#include <stdio.h>
#include <string.h>

typedef struct {
    char name[32];
    int quantity;
    double price;
} Item;

typedef struct {
    Item items[16];
    int count;
} Inventory;

int inventory_to_reorder(const Inventory *inv, int threshold, char names[][32], int max) {
    int n = 0;
    for (int i = 0; i < inv->count && n < max; i++) {
        if (inv->items[i].quantity <= threshold) {
            strcpy(names[n], inv->items[i].name);
            n++;
        }
    }
    return n;
}

int main(void) {
    Inventory inv = {
        .items = {{"Powdered milk", 3, 4.5}, {"Soap", 15, 0.8}, {"Candles", 0, 1.2}},
        .count = 3,
    };
    char names[8][32];
    int n = inventory_to_reorder(&inv, 5, names, 8);
    printf("%d item(s) to reorder\n", n);
    for (int i = 0; i < n; i++) {
        printf("- %s\n", names[i]);
    }
    return 0;
}
2 item(s) to reorder
- Powdered milk
- Candles

char names[][32] is an array of 32-character strings: the first dimension can stay empty in a parameter, the second is required so the compiler knows where each row starts.

Common mistakes:

  • Ignoring the max parameter: with more items to reorder than places in names, the function writes outside the caller's array.
  • Testing quantity < threshold: an item exactly at the threshold (5) would never be reported, whereas the specification says "less than or equal to".

Summary

  1. 1A clear interface: a structure and prefixed functions that return 0 or -1.
  2. 2Always validate before changing: a refused operation leaves no trace.
  3. 3Limiting every string copy (strlen before strcpy, %31[^;]) prevents overflows.
  4. 4Check fclose's return value: that's when data really reaches the disk.
  5. 5Never put a side effect in assert: it disappears with NDEBUG.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.