Skip to main content

Lesson 5 of 5

Mini Project Part 8 - Binary File Database

Build a command-line binary file database: add records, list all, search by ID, and delete by ID. Uses binary `fread`/`fwrite`, `fseek` for random access, `argc`/`argv` parsing (preview of Module 11's `getopt`), and robust `errno`/`perror` error handling throughout.

18 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Binary Database - append, list, search, delete

Binary Database - append, list, search, delete
/* db.c - binary record database
   Usage: ./db add "Alice" 88.5
          ./db list
          ./db search 1
          ./db delete 1                                    */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DB_FILE "records.bin"

typedef struct {
    int   id;
    char  name[32];
    float grade;
    int   deleted;   /* soft-delete flag */
} Record;

/* Generate next ID from max in file */
static int next_id(void) {
    FILE *fp = fopen(DB_FILE, "rb");
    if (!fp) return 1;
    int max_id = 0;
    Record r;
    while (fread(&r, sizeof(Record), 1, fp) == 1) {
        if (!r.deleted && r.id > max_id) max_id = r.id;
    }
    fclose(fp);
    return max_id + 1;
}

static int cmd_add(const char *name, float grade) {
    FILE *fp = fopen(DB_FILE, "ab");  /* append binary */
    if (!fp) { perror("fopen add"); return 1; }
    Record r = { next_id(), "", grade, 0 };
    strncpy(r.name, name, sizeof(r.name) - 1);
    fwrite(&r, sizeof(Record), 1, fp);
    fclose(fp);
    printf("Added: id=%d name=%s grade=%.1f
", r.id, r.name, r.grade);
    return 0;
}

static int cmd_list(void) {
    FILE *fp = fopen(DB_FILE, "rb");
    if (!fp) { printf("No records yet.
"); return 0; }
    Record r;
    printf("%-4s %-20s %s
", "ID", "Name", "Grade");
    printf("%-4s %-20s %s
", "----", "--------------------", "-----");
    while (fread(&r, sizeof(Record), 1, fp) == 1) {
        if (!r.deleted)
            printf("%-4d %-20s %.1f
", r.id, r.name, r.grade);
    }
    fclose(fp);
    return 0;
}

static int cmd_search(int id) {
    FILE *fp = fopen(DB_FILE, "rb");
    if (!fp) { printf("No records.
"); return 0; }
    Record r;
    while (fread(&r, sizeof(Record), 1, fp) == 1) {
        if (!r.deleted && r.id == id) {
            printf("Found: %d %s %.1f
", r.id, r.name, r.grade);
            fclose(fp); return 0;
        }
    }
    printf("ID %d not found
", id);
    fclose(fp);
    return 0;
}

static int cmd_delete(int id) {
    FILE *fp = fopen(DB_FILE, "r+b");
    if (!fp) { perror("fopen delete"); return 1; }
    Record r;
    while (fread(&r, sizeof(Record), 1, fp) == 1) {
        if (!r.deleted && r.id == id) {
            r.deleted = 1;
            fseek(fp, -(long)sizeof(Record), SEEK_CUR);
            fwrite(&r, sizeof(Record), 1, fp);
            printf("Deleted id=%d
", id);
            fclose(fp); return 0;
        }
    }
    printf("ID %d not found
", id);
    fclose(fp);
    return 0;
}

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s add|list|search|delete ...
", argv[0]);
        return 1;
    }
    if (strcmp(argv[1], "add") == 0 && argc == 4) {
        return cmd_add(argv[2], (float)atof(argv[3]));
    } else if (strcmp(argv[1], "list") == 0) {
        return cmd_list();
    } else if (strcmp(argv[1], "search") == 0 && argc == 3) {
        return cmd_search(atoi(argv[2]));
    } else if (strcmp(argv[1], "delete") == 0 && argc == 3) {
        return cmd_delete(atoi(argv[2]));
    } else {
        fprintf(stderr, "Unknown command or wrong arguments
");
        return 1;
    }
}
/* Build: gcc -Wall -Wextra -std=c99 db.c -o db
   ./db add "Alice" 88.5
   ./db add "Bob"   92.0
   ./db list
   ./db search 1
   ./db delete 1
   ./db list                                               */

Common Mistakes

  • Appending without record count header - this database uses open-ended append (no fixed-count header). Deletion is by soft-delete flag, avoiding the complexity of compacting the file. This is a valid real-world pattern.
  • Not rewinding before the soft-delete write - `fseek(fp, -(long)sizeof(Record), SEEK_CUR)` backs up by one record after the successful `fread`. Forgetting this overwrites the NEXT record instead of the current one.
  • Using `atof`/`atoi` without range/error checking - for production code, replace with `strtod`/`strtol` which report parse errors. `atof` silently returns 0.0 on invalid input.

Tip

Tip

Practice Mini Project Part 8 Binary File Database in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Binary database stores fixed-size records on disk, enabling O(1) indexed lookups via fseek

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Part 8 Binary File Database from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Part 8 Binary File Database is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • Build a command-line binary file database: add records, list all, search by ID, and delete by ID.
  • Appending without record count header - this database uses open-ended append (no fixed-count header). Deletion is by soft-delete flag, avoiding the complexity of compacting the file. This is a valid real-world pattern.
  • Not rewinding before the soft-delete write - `fseek(fp, -(long)sizeof(Record), SEEK_CUR)` backs up by one record after the successful `fread`. Forgetting this overwrites the NEXT record instead of the current one.
  • Using `atof`/`atoi` without range/error checking - for production code, replace with `strtod`/`strtol` which report parse errors. `atof` silently returns 0.0 on invalid input.

Topics in This Module

0/5 done