C: Final Project: Library Management

🗓 Last updated: 2026-11-30👤 Written by: Gray✓ Reviewed by: MOTO🏷 Category: C Tutorial

Building a house isn't just about learning to lay bricks — now it's time to combine all your skills and construct a complete building, from foundation to roof.

Reference entries in this section: static fgets scanf

1. Requirements Analysis

We'll build a command-line library management system with the following features:

  1. Add books (title, author, ISBN, price)
  2. Remove books (by ISBN)
  3. Update book information
  4. Search books (by title or ISBN)
  5. List all books
  6. Save data to file (persistence)
  7. Load data from file

2. Data Structure Design

Book information is represented by a struct, and all books are managed with a dynamic array:

C
// Type definition
typedef struct {
    char isbn[14];
    char title[128];
    char author[64];
    // Variable declaration
    double price;
} Book;

// Type definition
typedef struct {
    Book *books;
    // Variable declaration
    int count;
    // Variable declaration
    int capacity;
} Library;

Library manages a dynamic array: books is the data pointer, count is the current number of items, and capacity is the allocated capacity. When count reaches capacity, it automatically expands.


3. Project File Organization

C
bookmanager/
├── Makefile
├── main.c
├── library.h
├── library.c
├── storage.h
└── storage.c

4. library.h

C
// Preprocessor directive
#ifndef LIBRARY_H
// Preprocessor directive
#define LIBRARY_H

// Type definition
typedef struct {
    char isbn[14];
    char title[128];
    char author[64];
    // Variable declaration
    double price;
} Book;

// Type definition
typedef struct {
    Book *books;
    // Variable declaration
    int count;
    // Variable declaration
    int capacity;
} Library;

// Function definition
void library_init(Library *lib);
// Function definition
void library_free(Library *lib);
// Function definition
int library_add(Library *lib, const Book *book);
// Function definition
int library_remove(Library *lib, const char *isbn);
Book *library_find_by_isbn(Library *lib, const char *isbn);
// Function definition
void library_find_by_title(Library *lib, const char *keyword,
                           Book **results, int *result_count);
// Function definition
int library_update(Library *lib, const char *isbn, const Book *new_info);
// Function definition
void library_list(const Library *lib);

// Preprocessor directive
#endif

5. library.c

C
// Preprocessor directive
#include "library.h"
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <stdlib.h>
// Preprocessor directive
#include <string.h>

static int ensure_capacity(Library *lib) {
    // Conditional check
    if (lib->count < lib->capacity) {
        // Return result
        return 1;
    }
    // Variable declaration
    int new_cap = lib->capacity == 0 ? 4 : lib->capacity * 2;
    Book *new_books = realloc(lib->books, new_cap * sizeof(Book));
    // Conditional check
    if (new_books == NULL) {
        // Return result
        return 0;
    }
    lib->books = new_books;
    lib->capacity = new_cap;
    // Return result
    return 1;
}

// Function definition
void library_init(Library *lib) {
    lib->books = NULL;
    lib->count = 0;
    lib->capacity = 0;
}

// Function definition
void library_free(Library *lib) {
    // Dynamic memory operation
    free(lib->books);
    lib->books = NULL;
    lib->count = 0;
    lib->capacity = 0;
}

// Function definition
int library_add(Library *lib, const Book *book) {
    // Conditional check
    if (!ensure_capacity(lib)) {
        // Return result
        return 0;
    }
    lib->books[lib->count] = *book;
    lib->count++;
    // Return result
    return 1;
}

// Function definition
int library_remove(Library *lib, const char *isbn) {
    // For loop
    for (int i = 0; i < lib->count; i++) {
        // Conditional check
        if (strcmp(lib->books[i].isbn, isbn) == 0) {
            // For loop
            for (int j = i; j < lib->count - 1; j++) {
                lib->books[j] = lib->books[j + 1];
            }
            lib->count--;
            // Return result
            return 1;
        }
    }
    // Return result
    return 0;
}

Book *library_find_by_isbn(Library *lib, const char *isbn) {
    // For loop
    for (int i = 0; i < lib->count; i++) {
        // Conditional check
        if (strcmp(lib->books[i].isbn, isbn) == 0) {
            // Return result
            return &lib->books[i];
        }
    }
    // Return result
    return NULL;
}

// Function definition
void library_find_by_title(Library *lib, const char *keyword,
                           Book **results, int *result_count) {
    *result_count = 0;
    // For loop
    for (int i = 0; i < lib->count; i++) {
        // Conditional check
        if (strstr(lib->books[i].title, keyword) != NULL) {
            results[*result_count] = &lib->books[i];
            (*result_count)++;
        }
    }
}

// Function definition
int library_update(Library *lib, const char *isbn, const Book *new_info) {
    Book *existing = library_find_by_isbn(lib, isbn);
    // Conditional check
    if (existing == NULL) {
        // Return result
        return 0;
    }
    *existing = *new_info;
    // Return result
    return 1;
}

// Function definition
void library_list(const Library *lib) {
    // Conditional check
    if (lib->count == 0) {
        // I/O operation
        printf("No books in the library.\n");
        // Return result
        return;
    }
    // I/O operation
    printf("%-14s %-30s %-20s %-8s\n", "ISBN", "Title", "Author", "Price");
    // I/O operation
    printf("--------------------------------------------------------------\n");
    // For loop
    for (int i = 0; i < lib->count; i++) {
        // I/O operation
        printf("%-14s %-30s %-20s %-8.2f\n",
               lib->books[i].isbn,
               lib->books[i].title,
               lib->books[i].author,
               lib->books[i].price);
    }
    // I/O operation
    printf("Total: %d books\n", lib->count);
}
💡 Tip: ensure_capacity is an internal function, decorated with static to limit its scope to this file. The dynamic array doubling strategy is standard practice, guaranteeing amortized O(1) insertion efficiency.


6. storage.h

TEXT
#ifndef STORAGE_H
#define STORAGE_H

#include "library.h"

int storage_save(const Library *lib, const char *filename);
int storage_load(Library *lib, const char *filename);

#endif

7. storage.c

C
// Preprocessor directive
#include "storage.h"
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <string.h>

// Function definition
int storage_save(const Library *lib, const char *filename) {
    FILE *fp = fopen(filename, "w");
    // Conditional check
    if (fp == NULL) {
        // Return result
        return 0;
    }
    // For loop
    for (int i = 0; i < lib->count; i++) {
        fprintf(fp, "%s|%s|%s|%.2f\n",
                lib->books[i].isbn,
                lib->books[i].title,
                lib->books[i].author,
                lib->books[i].price);
    }
    // I/O operation
    fclose(fp);
    // Return result
    return 1;
}

// Function definition
int storage_load(Library *lib, const char *filename) {
    FILE *fp = fopen(filename, "r");
    // Conditional check
    if (fp == NULL) {
        // Return result
        return 1;
    }
    Book book;
    // While loop
    while (fscanf(fp, "%13[^|]|%127[^|]|%63[^|]|%lf\n",
                  book.isbn, book.title, book.author, &book.price) == 4) {
        // Conditional check
        if (!library_add(lib, &book)) {
            // I/O operation
            fclose(fp);
            // Return result
            return 0;
        }
    }
    // I/O operation
    fclose(fp);
    // Return result
    return 1;
}
⚠️ Note: fscanf's %[^|] format reads a string up to the | delimiter. %13[^|] limits the read to at most 13 characters, preventing overflow. This is the safe way to use formatted I/O.


8. main.c

TEXT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "library.h"
#include "storage.h"

#define DATA_FILE "library.dat"

static void input_string(const char *prompt, char *buf, int size) {
    printf("%s", prompt);
    fflush(stdout);
    if (fgets(buf, size, stdin) == NULL) {
        buf[0] = '\0';
        return;
    }
    buf[strcspn(buf, "\n")] = '\0';
}

static void cmd_add(Library *lib) {
    Book book;
    input_string("Enter ISBN: ", book.isbn, sizeof(book.isbn));
    input_string("Enter title: ", book.title, sizeof(book.title));
    input_string("Enter author: ", book.author, sizeof(book.author));

    char price_str[32];
    input_string("Enter price: ", price_str, sizeof(price_str));
    book.price = atof(price_str);

    if (library_find_by_isbn(lib, book.isbn) != NULL) {
        printf("Error: ISBN %s already exists\n", book.isbn);
        return;
    }

    if (library_add(lib, &book)) {
        printf("Added successfully!\n");
    } else {
        printf("Failed to add: out of memory\n");
    }
}

static void cmd_remove(Library *lib) {
    char isbn[14];
    input_string("Enter ISBN to remove: ", isbn, sizeof(isbn));

    if (library_remove(lib, isbn)) {
        printf("Removed successfully!\n");
    } else {
        printf("Book with that ISBN not found\n");
    }
}

static void cmd_find(Library *lib) {
    printf("1. Search by ISBN  2. Search by title\n");
    char choice[8];
    input_string("Choose: ", choice, sizeof(choice));

    if (strcmp(choice, "1") == 0) {
        char isbn[14];
        input_string("Enter ISBN: ", isbn, sizeof(isbn));
        Book *book = library_find_by_isbn(lib, isbn);
        if (book != NULL) {
            printf("ISBN:   %s\n", book->isbn);
            printf("Title:  %s\n", book->title);
            printf("Author: %s\n", book->author);
            printf("Price:  %.2f\n", book->price);
        } else {
            printf("Not found\n");
        }
    } else if (strcmp(choice, "2") == 0) {
        char keyword[128];
        input_string("Enter keyword: ", keyword, sizeof(keyword));
        Book *results[100];
        int result_count = 0;
        library_find_by_title(lib, keyword, results, &result_count);
        if (result_count == 0) {
            printf("No books containing \"%s\" found\n", keyword);
        } else {
            for (int i = 0; i < result_count; i++) {
                printf("%-14s %-30s %.2f\n",
                       results[i]->isbn, results[i]->title, results[i]->price);
            }
            printf("Found %d books\n", result_count);
        }
    }
}

static void cmd_update(Library *lib) {
    char isbn[14];
    input_string("Enter ISBN to update: ", isbn, sizeof(isbn));

    Book *existing = library_find_by_isbn(lib, isbn);
    if (existing == NULL) {
        printf("Book with that ISBN not found\n");
        return;
    }

    Book new_info = *existing;
    printf("Current title: %s (press Enter to keep)\n", existing->title);
    input_string("New title: ", new_info.title, sizeof(new_info.title));
    if (new_info.title[0] == '\0') {
        strcpy(new_info.title, existing->title);
    }

    printf("Current author: %s (press Enter to keep)\n", existing->author);
    input_string("New author: ", new_info.author, sizeof(new_info.author));
    if (new_info.author[0] == '\0') {
        strcpy(new_info.author, existing->author);
    }

    char price_str[32];
    printf("Current price: %.2f (press Enter to keep)\n", existing->price);
    input_string("New price: ", price_str, sizeof(price_str));
    if (price_str[0] != '\0') {
        new_info.price = atof(price_str);
    } else {
        new_info.price = existing->price;
    }

    strcpy(new_info.isbn, isbn);
    if (library_update(lib, isbn, &new_info)) {
        printf("Updated successfully!\n");
    }
}

static void show_menu(void) {
    printf("\n===== Library Management System =====\n");
    printf("1. Add book\n");
    printf("2. Remove book\n");
    printf("3. Search book\n");
    printf("4. Update book\n");
    printf("5. List all books\n");
    printf("6. Save data\n");
    printf("0. Exit\n");
    printf("=====================================\n");
}

int main(void) {
    Library lib;
    library_init(&lib);

    if (!storage_load(&lib, DATA_FILE)) {
        printf("Warning: Failed to load data, starting with empty library\n");
    }

    char choice[8];
    while (1) {
        show_menu();
        input_string("Choose an option: ", choice, sizeof(choice));

        if (strcmp(choice, "1") == 0) {
            cmd_add(&lib);
        } else if (strcmp(choice, "2") == 0) {
            cmd_remove(&lib);
        } else if (strcmp(choice, "3") == 0) {
            cmd_find(&lib);
        } else if (strcmp(choice, "4") == 0) {
            cmd_update(&lib);
        } else if (strcmp(choice, "5") == 0) {
            library_list(&lib);
        } else if (strcmp(choice, "6") == 0) {
            if (storage_save(&lib, DATA_FILE)) {
                printf("Saved successfully!\n");
            } else {
                printf("Failed to save!\n");
            }
        } else if (strcmp(choice, "0") == 0) {
            printf("Save data before exiting? (y/n): ");
            char confirm[8];
            if (fgets(confirm, sizeof(confirm), stdin) != NULL) {
                if (confirm[0] == 'y' || confirm[0] == 'Y') {
                    storage_save(&lib, DATA_FILE);
                    printf("Saved\n");
                }
            }
            break;
        } else {
            printf("Invalid choice\n");
        }
    }

    library_free(&lib);
    return 0;
}

9. Makefile

MAKEFILE
CC = gcc
CFLAGS = -Wall -Wextra -std=c99 -O2
SRCS = main.c library.c storage.c
OBJS = $(SRCS:.c=.o)
TARGET = bookmanager

$(TARGET): $(OBJS)
	$(CC) $(CFLAGS) -o $@ $^

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

main.o: main.c library.h storage.h
library.o: library.c library.h
storage.o: storage.c storage.h library.h

clean:
	rm -f $(OBJS) $(TARGET)

.PHONY: clean

Build and run:

BASH
make
./bookmanager

10. Running the Program

TEXT
===== Library Management System =====
1. Add book
2. Remove book
3. Search book
4. Update book
5. List all books
6. Save data
0. Exit
=====================================
Choose an option: 1
Enter ISBN: 9787115279460
Enter title: C Primer Plus
Enter author: Stephen Prata
Enter price: 89.00
Added successfully!

Choose an option: 5
ISBN           Title                          Author               Price
--------------------------------------------------------------
9787115279460  C Primer Plus                  Stephen Prata        89.00
Total: 1 books

11. Key Project Insights

(1) Dynamic Array Expansion

ensure_capacity uses a doubling strategy. Each time count reaches capacity, the capacity doubles. This means n insertions cause O(log n) total reallocations, giving amortized O(1) per insertion.

(2) File Format Choice

The storage format uses |-delimited text rather than binary. Benefits:

(3) Module Separation

library and storage are decoupled — core logic doesn't depend on the specific storage method. Switching to a database later only requires modifying storage.c, with no changes to the core code.

(4) Input Safety

input_string uses fgets for input, automatically limiting length, then removes the newline with strcspn. This is a safer input method than scanf.

▶ Example

▶ Try it Yourself
TEXT
ID:1 Title:C Primer Plus Author:Stephen Prata

▶ Example — extern cross-file variable

▶ Try it Yourself
C
// library.c
#include "library.h"

Book current_shelf;           // definition — linker sees one copy
C
// main.c
#include "library.h"
int main(void) {
    strcpy(current_shelf.title, "K&R C");
    printf("%s\n", current_shelf.title);
    return 0;
}
TEXT
K&R C

▶ Example — static function with file-local scope

▶ Try it Yourself

Output: (function compiles successfully when included in library.c, no standalone output)

Reference entries in this section: static fgets scanf

❓ FAQ

Q How do I use extern to share variables between source files?
A Put the variable declaration with the extern keyword in a header file, and put the actual definition (without extern, with an optional initializer) in exactly one .c file. The linker will merge all references into a single memory location. Declare in header as extern Book shelf;, define once in one .c as Book shelf;.
Q Should I cast the result of malloc (in C)?
A No. malloc returns void *, which C automatically converts to any pointer type. Casting makes no difference to correctness and is considered redundant in pure C (C++ requires the cast, but that is a different language). If you ever see a cast on malloc, it is usually leftover from old C++ habits.
Q Difference between malloc and calloc?
A malloc(bytes) allocates uninitialized memory — the contents are whatever was left there before, which can cause bugs if you forget to initialize. calloc(n, element_size) allocates n times element_size bytes and zeroes every byte. calloc is slightly slower but safer; malloc is faster when you are going to overwrite the memory immediately anyway.
Q How do I determine the size of my array in C?
A For a local array (one declared on the stack), use sizeof(arr) / sizeof(arr[0]). For a pointer returned by malloc, the pointer itself has no size information — you must keep a separate counter variable (count or capacity). That is exactly why the Library struct in this project stores both count and capacity.
Q What is a segmentation fault?
A A segfault happens when your program tries to read or write memory it is not allowed to touch. Common causes in this project: dereferencing a NULL pointer (e.g. library_find_by_isbn returns NULL and you do ptr->title), going out of bounds on the books array, or calling library_free twice (double-free corrupts the heap). Run with valgrind or AddressSanitizer to find the exact line.
Q What does "static" mean in C?
A In this project we use static on ensure_capacity inside library.c. That means the function has file-local scope — only code in that one .c file can call it, and two different .c files can each have their own static function with the same name without colliding. static on a file-level variable does the same thing, and inside a function it means the variable persists across function calls.
Q What is the difference between ++i and i++?
A Both increment i by 1, but they return different values. ++i (pre-increment) increments first, then returns the new value. i++ (post-increment) returns the old value, then increments. In a for loop like for (int i = 0; i < n; i++) the final value is thrown away anyway, so either is fine — but ++i is usually the idiomatic C choice in modern code.
Q How to generate a random int in C?
A rand() from stdlib.h returns an integer between 0 and RAND_MAX. Seed it once with srand((unsigned)time(NULL)) at the start of your program, otherwise you get the same sequence every run. To get a range like [0, 99], use rand() % 100. Note that rand() is not cryptographically secure, so do not use it for security-sensitive applications.

📖 Summary

📝 Exercises

  1. Add a "search by author" feature to the library management system
  2. Add sorting functionality to display books sorted by title, price, or ISBN
  3. Improve the storage module by switching to binary file format and compare the pros and cons versus text format
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏