Skip to content
StudyFame

Library Management System in C

A library needs to know which books it has, which ones are issued and to whom, and which are available. That makes it a perfect second record-based project. It uses the same file techniques as the student system, plus two new ideas: a status field that changes over time (available → issued → available) and searching inside text.

In this project you will build a library system that stores books in a binary file, lets you add, list, search, issue and return books, and then write a late return fine calculator.

What You Will Learn

  • How to design a record with a status field.
  • How to read titles with spaces using scanf(" %[^\n]").
  • How to search a title for a word with strstr().
  • How to issue and return a book by updating a record in place.
  • How to prevent invalid actions (issuing an issued book).
  • How to calculate a fine with slabs.

Library Management System in C Explained

Exam definition: A library management system maintains book records, each with an ID, title, author and status (available or issued, with the borrower's name). Issuing a book changes its status to issued if it is currently available; returning changes it back. Each change is saved by updating the record in the file (read, modify, seek back, write), so the library's state survives between runs.

Memory trick: Every book card has a small flag: green = on the shelf, red = with a student. Issue = turn green to red and write the student's name. Return = turn red back to green. The system's job is to never turn a red flag red again (can't issue an issued book).

struct book
{
    int id;
    char title[50];
    char author[30];
    int issued;              /* 0 = available, 1 = issued */
    char borrower[30];
};

scanf(" %49[^\n]", b.title);        /* read a whole line, spaces included */
if (strstr(b.title, "C") != NULL)   /* does the title contain "C"? */
    ...

%[^\n] means "read every character that is not a newline", and the space before it skips leftover newlines. 49 limits the length to fit title[50].

Example 1: Library Management System

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

#define FILE_NAME "books.dat"

struct book
{
    int id;
    char title[50];
    char author[30];
    int issued;
    char borrower[30];
};

void add_book(void)
{
    struct book b = {0};
    FILE *fp;

    printf("Book ID: ");
    if (scanf("%d", &b.id) != 1) return;
    printf("Title  : ");
    scanf(" %49[^\n]", b.title);
    printf("Author : ");
    scanf(" %29[^\n]", b.author);
    fp = fopen(FILE_NAME, "ab");
    if (fp == NULL) return;
    fwrite(&b, sizeof b, 1, fp);
    fclose(fp);
    printf("Book saved.\n");
}

void list_books(void)
{
    struct book b;
    FILE *fp = fopen(FILE_NAME, "rb");
    if (fp == NULL) { printf("No books.\n"); return; }
    printf("%-3s %-24s %-13s %s\n", "ID", "Title", "Author", "Status");
    while (fread(&b, sizeof b, 1, fp) == 1)
    {
        printf("%-3d %-24s %-13s ", b.id, b.title, b.author);
        if (b.issued)
            printf("Issued to %s\n", b.borrower);
        else
            printf("Available\n");
    }
    fclose(fp);
}

void search_title(void)
{
    struct book b;
    char word[30];
    FILE *fp = fopen(FILE_NAME, "rb");
    int found = 0;

    printf("Word in title: ");
    scanf(" %29[^\n]", word);
    if (fp == NULL) return;
    while (fread(&b, sizeof b, 1, fp) == 1)
        if (strstr(b.title, word) != NULL)
        {
            printf("  [%d] %s by %s\n", b.id, b.title, b.author);
            found++;
        }
    printf("%d match(es) found\n", found);
    fclose(fp);
}

/* issue = 1 to issue, 0 to return */
void change_status(int issue)
{
    struct book b;
    FILE *fp = fopen(FILE_NAME, "rb+");
    int id;

    printf("Book ID: ");
    if (scanf("%d", &id) != 1 || fp == NULL) { if (fp) fclose(fp); return; }
    while (fread(&b, sizeof b, 1, fp) == 1)
    {
        if (b.id != id)
            continue;
        if (issue && b.issued)
            printf("Sorry, '%s' is already issued to %s.\n", b.title, b.borrower);
        else if (!issue && !b.issued)
            printf("'%s' was not issued.\n", b.title);
        else
        {
            if (issue)
            {
                printf("Student name: ");
                scanf(" %29[^\n]", b.borrower);
                b.issued = 1;
                printf("'%s' issued to %s.\n", b.title, b.borrower);
            }
            else
            {
                printf("'%s' returned by %s.\n", b.title, b.borrower);
                b.issued = 0;
                b.borrower[0] = '\0';
            }
            fseek(fp, -(long) sizeof b, SEEK_CUR);
            fwrite(&b, sizeof b, 1, fp);
        }
        fclose(fp);
        return;
    }
    printf("No book with that ID.\n");
    fclose(fp);
}

int main(void)
{
    int choice;

    while (1)
    {
        printf("\n1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit\nChoice: ");
        if (scanf("%d", &choice) != 1 || choice == 0)
            break;
        switch (choice)
        {
        case 1: add_book(); break;
        case 2: list_books(); break;
        case 3: search_title(); break;
        case 4: change_status(1); break;
        case 5: change_status(0); break;
        default: printf("Invalid choice\n");
        }
    }
    printf("Library closed.\n");
    return 0;
}

Output

1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit
Choice: 1
Book ID: 1
Title  : Let Us C
Author : Kanetkar
Book saved.

1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit
Choice: 1
Book ID: 2
Title  : Programming in ANSI C
Author : Balagurusamy
Book saved.

1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit
Choice: 1
Book ID: 3
Title  : Data Structures
Author : Tanenbaum
Book saved.

1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit
Choice: 4
Book ID: 1
Student name: Riya
'Let Us C' issued to Riya.

1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit
Choice: 4
Book ID: 1
Sorry, 'Let Us C' is already issued to Riya.

1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit
Choice: 3
Word in title: ANSI
  [2] Programming in ANSI C by Balagurusamy
1 match(es) found

1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit
Choice: 5
Book ID: 1
'Let Us C' returned by Riya.

1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit
Choice: 5
Book ID: 1
'Let Us C' was not issued.

1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit
Choice: 2
ID  Title                    Author        Status
1   Let Us C                 Kanetkar      Available
2   Programming in ANSI C    Balagurusamy  Available
3   Data Structures          Tanenbaum     Available

1.Add 2.List 3.Search 4.Issue 5.Return 0.Exit
Choice: 0
Library closed.

Code Explanation

  1. struct book has an issued flag and a borrower name. = {0} starts a new book as available with empty strings.
  2. scanf(" %49[^\n]", ...) reads full titles like "Programming in ANSI C". Plain %s would stop at the first space.
  3. search_title uses strstr(title, word), which returns a pointer to the word inside the title, or NULL if it isn't there. (It is case-sensitive.)
  4. Issue and return share one function, change_status(issue), because both find a book, check its current status, change it and save it in place.
  5. The checks stop impossible actions: issuing an issued book or returning a book that is on the shelf. In the run, the second issue request is refused because Riya already has the book, so no student name is asked.
  6. Saving uses the same pattern as before: fseek back one record and fwrite.

How a Book Moves Through the System

              issue (if available)
  AVAILABLE ──────────────────────► ISSUED (borrower = name)
      ▲                                  │
      └──────────────────────────────────┘
              return (if issued)

issue an ISSUED book   -> refused
return an AVAILABLE book -> refused

Thinking of records as moving between states like this makes rules easy to code: each action is allowed only from certain states. Real systems add more states (reserved, lost, under repair).

Example 2: Late Return Fine Calculator

#include <stdio.h>

#define FREE_DAYS 14

/* Rs 2 per day for the first 7 late days, Rs 5 per day after that, max Rs 200 */
int late_fine(int days_kept)
{
    int late = days_kept - FREE_DAYS, fine;

    if (late <= 0)
        return 0;
    if (late <= 7)
        fine = late * 2;
    else
        fine = 7 * 2 + (late - 7) * 5;
    return fine > 200 ? 200 : fine;
}

int main(void)
{
    int days[] = {10, 14, 18, 21, 30, 90};
    int i;

    printf("Days kept  Late days  Fine (Rs)\n");
    for (i = 0; i < 6; i++)
    {
        int late = days[i] - FREE_DAYS;
        printf("%9d  %9d  %9d\n", days[i], late > 0 ? late : 0, late_fine(days[i]));
    }
    return 0;
}

Output

Days kept  Late days  Fine (Rs)
       10          0          0
       14          0          0
       18          4          8
       21          7         14
       30         16         59
       90         76        200
  • The first 14 days are free. 18 days = 4 late days × Rs 2 = Rs 8.
  • 30 days = 16 late days: 7 × 2 + 9 × 5 = 14 + 45 = Rs 59 (a slab system, like electricity bills).
  • The fine is capped at Rs 200, so 90 days still costs 200.
  • In the full system you would store the issue date in the record and compute days kept when the book is returned.

Important Points to Remember

  • Give each record a status field (issued flag) and update it in place.
  • Read text with spaces using scanf(" %49[^\n]", s) or fgets.
  • strstr(text, word) finds a word inside a string (NULL if absent).
  • Validate actions against the current status before changing it.
  • Reuse one function for similar actions (issue/return) to avoid duplicate code.
  • Slab calculations: handle each range separately and apply a cap if needed.

Common Mistakes Beginners Make

MistakeWhat happensFix
scanf("%s", title)"Let Us C" stored as "Let"; the rest breaks later inputscanf(" %49[^\n]", title)
No space before %[^\n]Reads the leftover newline: empty titleWrite " %[^\n]" with a space
Not checking the status before issuingTwo students "have" the same bookRefuse if issued == 1
Forgetting to clear the borrower on returnOld names appear in reportsborrower[0] = '\0'
Expecting strstr to ignore caseSearching "ansi" doesn't find "ANSI"Convert both strings to one case first

Library Management System Practice Questions

  1. Which fields does a book record need for issue and return?
  2. How does scanf(" %49[^\n]", s) work?
  3. What does strstr() return?
  4. Which two invalid actions does the program prevent?
  5. Calculate the fine for keeping a book 25 days with the rules from Example 2.
Show answers
  1. An issued/available flag and the borrower's name (plus id, title, author).
  2. The space skips whitespace, %[^\n] reads all characters up to the newline, and 49 limits the length.
  3. A pointer to the first occurrence of the word in the string, or NULL if not found.
  4. Issuing a book that is already issued, and returning a book that is not issued.
  5. 11 late days: 7 × 2 + 4 × 5 = 14 + 20 = Rs 34.

Coding Exercise

Write a function void to_lower_str(char *s) and use it to make the title search case-insensitive. Search the titles "Let Us C", "Programming in ANSI C" and "Data Structures" for the word "ansi" and the word "c".

Show solution
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void to_lower_str(char *s)
{
    for (; *s; s++)
        *s = (char) tolower((unsigned char) *s);
}

int contains_ignore_case(const char *text, const char *word)
{
    char t[60], w[30];
    strcpy(t, text);
    strcpy(w, word);
    to_lower_str(t);
    to_lower_str(w);
    return strstr(t, w) != NULL;
}

int main(void)
{
    const char *titles[] = {"Let Us C", "Programming in ANSI C", "Data Structures"};
    const char *words[] = {"ansi", "c"};
    int i, j;

    for (j = 0; j < 2; j++)
    {
        printf("Search \"%s\":", words[j]);
        for (i = 0; i < 3; i++)
            if (contains_ignore_case(titles[i], words[j]))
                printf(" [%s]", titles[i]);
        printf("\n");
    }
    return 0;
}
Search "ansi": [Programming in ANSI C]
Search "c": [Let Us C] [Programming in ANSI C] [Data Structures]

"Data Structures" matches "c" because it contains "c" in "Structures": a simple substring search, not a whole-word search.

Quick Quiz: Library Management System (MCQ)

  1. Which format reads a line with spaces?

    A) %s   B) %c   C) %[^\n]   D) %d

  2. strstr("Let Us C", "Us") returns:

    A) NULL   B) A pointer to "Us C"   C) 4   D) 1

  3. Issuing a book that is already issued should:

    A) Overwrite the borrower   B) Be refused   C) Delete the book   D) Crash

  4. Which mode lets the program update the issued flag in the file?

    A) "ab"   B) "rb+"   C) "wb"   D) "r"

  5. Which header declares strstr()?

    A) stdio.h   B) string.h   C) ctype.h   D) stdlib.h

Show answers
  1. C: %[^\n].
  2. B: a pointer to "Us C".
  3. B: be refused.
  4. B: "rb+".
  5. B: string.h.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Book recordid, title, author, issued flag, borrower
Title with spacesscanf(" %49[^\n]", s)
Search in textstrstr(), NULL if not found
IssueOnly if available; set flag and name
ReturnOnly if issued; clear flag and name
Save change"rb+", fseek back, fwrite
FineSlabs + cap

Frequently asked questions

What are the main features of a library management system in C?
Add, list, search, issue and return books, with records stored in a file.
How do you read a book title with spaces in C?
Use scanf(" %[^\n]", title) with a size limit, or fgets.
How does the program know if a book is issued?
Each record has an issued flag (0 or 1) that is updated in the file on issue and return.

Remember

  • Book card flag: green on shelf, red with student.
  • Check the state before every change.

Next Topic

Next lesson: Bank Management System in C. You will build a bank system with accounts, deposits, withdrawals and balance checks.