Reading history

C Project: Student Records System with Structs and Files

7 min read 0 views

Build a student records program in C using structs, CSV file saving and loading with fprintf, fgets and sscanf, qsort sorting, searching and deleting.

This project brings together many C topics in one working program: a student records system that stores students in an array of structures, saves them to a text file, loads them back, sorts them by CGPA, calculates the average, searches by ID and deletes records. Reading it from top to bottom is a good review of how structures, pointers, file handling and library functions fit together in a real program.

In this project you will practise

  • Designing data with typedef struct
  • Passing structures by pointer (and const pointer)
  • Writing a CSV file with fprintf and reading it with fgets and sscanf
  • Sorting with qsort and a custom comparator
  • Searching, deleting and computing statistics

The Complete Program

/* Student Records: a small console project using structs, files, qsort and sscanf */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 50
#define FILE_NAME "students.txt"

typedef struct {
    int id;
    char name[32];
    char dept[8];
    double cgpa;
} Student;

typedef struct {
    Student items[MAX];
    int count;
} Database;

static int add_student(Database *db, int id, const char *name, const char *dept, double cgpa) {
    if (db->count == MAX) return 0;
    for (int i = 0; i < db->count; i++)
        if (db->items[i].id == id) return 0;            /* ids must be unique */
    Student *s = &db->items[db->count++];
    s->id = id;
    snprintf(s->name, sizeof s->name, "%s", name);     /* safe copy, always terminated */
    snprintf(s->dept, sizeof s->dept, "%s", dept);
    s->cgpa = cgpa;
    return 1;
}

static int save(const Database *db, const char *path) {
    FILE *f = fopen(path, "w");
    if (!f) { perror("save"); return 0; }
    for (int i = 0; i < db->count; i++) {
        const Student *s = &db->items[i];
        fprintf(f, "%d,%s,%s,%.2f\n", s->id, s->name, s->dept, s->cgpa);
    }
    fclose(f);
    return 1;
}

static int load(Database *db, const char *path) {
    FILE *f = fopen(path, "r");
    if (!f) { perror("load"); return 0; }
    char line[128];
    db->count = 0;
    while (fgets(line, sizeof line, f)) {
        int id; char name[32], dept[8]; double cgpa;
        if (sscanf(line, "%d,%31[^,],%7[^,],%lf", &id, name, dept, &cgpa) == 4)
            add_student(db, id, name, dept, cgpa);
    }
    fclose(f);
    return 1;
}

static const Student *find_by_id(const Database *db, int id) {
    for (int i = 0; i < db->count; i++)
        if (db->items[i].id == id) return &db->items[i];
    return NULL;
}

static int remove_by_id(Database *db, int id) {
    for (int i = 0; i < db->count; i++) {
        if (db->items[i].id == id) {
            db->items[i] = db->items[--db->count];      /* move last record into the gap */
            return 1;
        }
    }
    return 0;
}

static int by_cgpa_desc(const void *a, const void *b) {
    const Student *x = a, *y = b;
    return (y->cgpa > x->cgpa) - (y->cgpa < x->cgpa);
}

static void print_all(const Database *db) {
    printf("%-4s %-10s %-5s %s\n", "ID", "Name", "Dept", "CGPA");
    for (int i = 0; i < db->count; i++) {
        const Student *s = &db->items[i];
        printf("%-4d %-10s %-5s %.2f\n", s->id, s->name, s->dept, s->cgpa);
    }
}

static double average(const Database *db) {
    if (db->count == 0) return 0;
    double sum = 0;
    for (int i = 0; i < db->count; i++) sum += db->items[i].cgpa;
    return sum / db->count;
}

int main(void) {
    Database db = {.count = 0};
    add_student(&db, 101, "Nusrat", "CSE", 3.82);
    add_student(&db, 102, "Arif", "EEE", 3.41);
    add_student(&db, 103, "Tania", "CSE", 3.95);
    add_student(&db, 104, "Rafi", "EEE", 2.98);
    printf("duplicate id 101 accepted? %s\n",
           add_student(&db, 101, "Copy", "CSE", 4.0) ? "yes" : "no");

    save(&db, FILE_NAME);
    Database loaded;
    load(&loaded, FILE_NAME);
    printf("loaded %d records from %s\n\n", loaded.count, FILE_NAME);

    qsort(loaded.items, (size_t)loaded.count, sizeof(Student), by_cgpa_desc);
    print_all(&loaded);
    printf("\naverage CGPA: %.2f\n", average(&loaded));

    const Student *s = find_by_id(&loaded, 102);
    printf("find 102: %s\n", s ? s->name : "not found");
    printf("remove 104: %s\n", remove_by_id(&loaded, 104) ? "done" : "not found");
    printf("find 104: %s\n", find_by_id(&loaded, 104) ? "found" : "not found");
    printf("records left: %d\n", loaded.count);

    remove(FILE_NAME);
    return 0;
}

Output

duplicate id 101 accepted? no
loaded 4 records from students.txt

ID   Name       Dept  CGPA
103  Tania      CSE   3.95
101  Nusrat     CSE   3.82
102  Arif       EEE   3.41
104  Rafi       EEE   2.98

average CGPA: 3.54
find 102: Arif
remove 104: done
find 104: not found
records left: 3

How It Works

  • Data design. Student holds one record and Database holds a fixed array of 50 plus a count. Keeping the count next to the array means every function receives everything it needs through one pointer. (See typedef.)
  • Pointers and const. Functions that change the database take Database *; functions that only read it, such as print_all and average, take const Database *, so the compiler stops them modifying it by mistake (see const).
  • Safe strings. snprintf(s->name, sizeof s->name, "%s", name) copies a name without ever overflowing the 32-byte field, and always terminates it.
  • Validation. add_student rejects a full database and duplicate IDs, which the first output line confirms.
  • Saving. Each record becomes one comma-separated line, for example 101,Nusrat,CSE,3.82. A text format is easy to inspect, edit in a spreadsheet and move between computers.
  • Loading. fgets reads one line at a time, and sscanf with %31[^,] reads text up to the next comma while limiting the length to fit the buffer. Lines that do not match all four fields are skipped.
  • Error handling. If fopen fails, perror prints the reason, for example “No such file or directory”.
  • Sorting. qsort with by_cgpa_desc orders students from highest to lowest CGPA (see qsort).
  • Deleting. remove_by_id copies the last record into the deleted slot and reduces the count. This takes constant time but changes the order; shift the remaining elements instead if order matters.
  • Clean-up. The demo deletes the data file at the end with remove(); a real program would keep it.

Ideas to Extend the Project

FeatureTopics you will use
A text menu that reads choices with fgets and strtolString conversion, loops, switch
Command-line options such as ./records add 105 Mitu CSE 3.67argc and argv
Unlimited records with a growing arraymalloc and realloc
Search by name ignoring caseString functions
Report per departmentSorting by two keys, loops

Common Mistakes in Projects Like This

  1. Using strcpy or %s without a width, which overflows fixed-size fields on long input.
  2. Not checking fopen and crashing when the file is missing.
  3. Forgetting fclose, which can leave written data unsaved.
  4. Using scanf("%d") for menus and getting stuck when the user types a letter; read whole lines with fgets instead.

Practice Exercises

Exercise 1. Add a function that prints only the students of one department.

Show answer
static void print_dept(const Database *db, const char *dept) {
    for (int i = 0; i < db->count; i++)
        if (strcmp(db->items[i].dept, dept) == 0)
            printf("%d %s\n", db->items[i].id, db->items[i].name);
}

Exercise 2. Change remove_by_id so the remaining records keep their order.

Show answer
for (int i = 0; i < db->count; i++) {
    if (db->items[i].id == id) {
        memmove(&db->items[i], &db->items[i + 1],
                (size_t)(db->count - i - 1) * sizeof(Student));
        db->count--;
        return 1;
    }
}
return 0;

Frequently Asked Questions

Why use a text file instead of fwrite with binary structs?

Text files are portable and human-readable, and they avoid problems with structure padding and byte order. Binary files are smaller and faster but tied to one compiler and platform.

How would a real application store this data?

Larger programs use a database. The C library for SQLite lets the same program store students in tables and query them with SQL.

Summary

  • Structures plus a count make a simple in-memory database.
  • Pass by pointer, and use const for read-only access.
  • Save as CSV with fprintf; load with fgets and a width-limited sscanf.
  • qsort, searching and deletion complete the feature set.

Next: Linked List in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *