Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 135 ยท Projects

Project: Library Management System

Build a library system in C: an array of book structs with issue, return and search, then binary file persistence and a command loop that saves and reloads the shelf.

A library is a small database: a list of records, each with a few fields, and a handful of operations on them. You add a book, find a book, lend it to a member, take it back. Almost every "management system" project (students, products, employees) has the same shape, so this one is worth building carefully. It is also the first project in this track where data has to survive the end of the program.

The project uses structures, arrays, string functions, enums, binary file I/O and fgets-based input. There are two stages: the records and their rules in memory, then saving, loading and a command loop.

Stage 1: records and rules in memory

One struct per book. A book has an id, a title, an author, and a record of who has it. Instead of a separate bool issued plus a member field that could disagree, one field does both jobs: borrower is 0 when the book is on the shelf and the member's number otherwise. A design where two fields can contradict each other is a bug waiting to happen, and removing the possibility is cheaper than checking for it.

One struct for the whole library. The books live in a fixed array inside struct Library, next to the count of used slots and next_id, the number the next new book will get. Passing a pointer to this one struct is easier than passing three loose variables everywhere. It also makes saving to disk simple, as you will see in Stage 2. Ids are never reused: if book 3 were removed later, a new book would not take the number 3, which keeps old receipts meaningful.

Return codes instead of printing. issue_book and return_book do not print anything. They return a value from an enum Result (OK, NOT_FOUND, ALREADY_ISSUED, NOT_ISSUED, FULL) and the caller decides what to say. This is the same split you used in error handling: the function reports, the caller reacts. It also makes the functions testable, since the checks in main just compare return values with what is expected.

Searching. A title search should find "Pragmatic" in "The Pragmatic Programmer" whatever the case. C has no standard case-insensitive strstr, so contains_ignore_case lowers one character at a time with tolower, comparing at every start position. The cast to unsigned char before tolower matters: passing a negative char to <ctype.h> functions is undefined behavior.

Why static helpers and const. find_by_id returns a pointer into the array, or NULL. Every operation starts with it, so the "no such book" case is handled in exactly one place. The text parameters are const char * because the functions only read them.

C Stage 1: add, issue, return and search

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.

Notice that the second issue to a different member fails: the rule "one copy, one borrower" is enforced in one function and nowhere else. The search for "the" matches "The C Programming Language" and "The Pragmatic Programmer" (in any case), but not "Code Complete". Run it and check which lines appear.

Stage 2: saving, loading and a command loop

Why a binary file. A text file would need a format, a parser, and escaping for titles that contain your separator character. Because the whole library is one struct with plain data in it (arrays and integers, no pointers), fwrite can copy it to disk as it is and fread can bring it back. The file is not readable in an editor, and it is only valid for the same struct layout, but the code is a few lines long. This is exactly the trade-off that binary files are about. If your struct held a char *, only the pointer value would be saved, which is meaningless after a restart; that is why every field here is a fixed-size array.

A header guards against garbage. The file starts with a 4-byte magic text (LIB1), then the count and the next id, then only the used books. load_library checks every step: the file opens, the magic matches, the count is between 0 and MAX_BOOKS, and fread returned as many records as expected. A file that fails any check is rejected and the library starts empty, because trusting a count read from disk would let a damaged file write past the end of the array. The 1 in LIB1 is a version number: if you change the struct, call it LIB2 and old files will be rejected instead of being misread.

Saving safely. save_library writes a temporary file and renames it over the real one, so a crash in the middle of saving cannot destroy the previous good copy. fclose can fail too (a full disk reports the error late), so its result is checked as well.

Parsing commands. The loop reads one line with fgets and splits it into a command word and the rest. sscanf with %15s%n reads the word (at most 15 characters, so it cannot overflow) and %n stores how many characters it used, so the rest of the line is line + used. After that, each command parses its own arguments: issue 2 7 uses sscanf(arg, "%d %d", ...), and add Title;Author splits at the semicolon with strchr. Every sscanf result is checked, so issue banana produces a usage message and not a book with garbage ids.

Proving persistence. A program on this page always starts with no library.dat, because each run gets a fresh directory. So at the end, the demo does what a restart would do: it loads the file into a second struct Library and lists it. If the lists match, saving and loading work.

C Stage 2: a command loop with save and load

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 output from the top. The error lines show the checks working: a second issue for book 2, an unknown id, and issue banana all fail politely without changing anything. The list at the very end comes from the file, not from memory.

Ideas for going further

  • Remove a book. Shift the later books down with memmove, decrement count, and refuse if the book is issued. Notice why ids are never reused.
  • Due dates. Add a time_t due to the struct (see time and date), set it to 14 days after issue and print overdue books in list.
  • A member table. Replace the bare member number with a second array of members and check that the member exists before issuing.
  • Sorting. Add sort title using qsort with a comparison function, as in sorting algorithms.
  • A text export. Write export that saves a CSV file, and think about what has to be quoted when a title contains a comma.
  • A limit per member. Count how many books a member holds and refuse a fourth.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the struct use one borrower field (0 = on the shelf) instead of a bool issued plus a member field?

    Data that can be in a contradictory state needs extra code to keep it consistent. One field makes the contradiction impossible.
  2. 2. Why can fwrite save the whole struct Library in one call?

    fwrite copies bytes. Arrays and integers inside the struct are the data itself. A char pointer would save only an address that is meaningless in the next run.
  3. 3. load_library checks count >= 0 && count <= MAX_BOOKS before reading the books. Why?

    Values read from a file are input and must be validated like any other. An unchecked count turns a corrupt file into a buffer overflow.
  4. 4. What does the %n in sscanf(line, "%15s%n", cmd, &used) store?

    %n does not read anything. It stores the count of characters processed up to that point, which is how the code finds where the arguments begin.
  5. 5. Why does save_library write to a temporary file and then call rename?

    The old file stays intact until the new one is complete. rename then replaces it in one step.

Summary

  • A record-based program is a struct, an array of them, and a few functions: find, add, change, list.
  • Represent state so that contradictions cannot occur (one borrower field, not two that must agree).
  • Let operations return an enum result and let the caller decide what to print.
  • A struct with no pointers can be saved with one fwrite and loaded with one fread. Put a magic header and a version in the file, and validate every value you read back.
  • Write to a temporary file and rename it over the old one, and check the result of fclose.
  • Parse commands with fgets and sscanf, check every result, and print a usage message for bad input.

Next: the quiz game project, where questions come from a file and are shuffled.