Skip to content
Tutorials Center
My learning

Topics

Lesson 111 of 135 ยท Projects

Project: Student Records

Build a student records manager in C - validated CSV parsing, a growable array of structs, sorting with qsort, bsearch lookups, and saving and loading files safely.

Almost every real program manages records: customers, orders, books, sensor readings, students. The details change, but the shape of the work is the same everywhere. You define a structure for one record, keep a collection of them in memory, validate data coming in, sort and search it, compute summaries, and save everything to a file so it survives until next time. Learning to do this well in C, where you manage every byte yourself, teaches you what databases and high-level languages do for you behind the scenes.

In this project you'll build a small student records manager. Each student has an ID, a name and three test scores. The program reads records as comma-separated lines, rejects bad ones with a clear reason, ranks and searches students, prints statistics, and finally becomes a command-driven tool that saves the class to a CSV file and loads it back. You'll build it in three stages, each a complete program, using everything from structures, arrays of structures, dynamic memory, qsort and bsearch, string conversions and text files.

The plan

The data model comes first. One student is a struct, and the class is a dynamic array of them, a struct that tracks a heap-allocated block, how many records it holds and how many it has room for:

C
typedef struct {
    int id;
    char name[NAME_SIZE];
    int scores[SCORE_COUNT];
    double average;
} student;

typedef struct {
    student *items;
    size_t count;
    size_t capacity;
} student_list;

The name is a fixed-size array inside the struct rather than a char * to a separate allocation. That's a deliberate trade-off: it wastes a few bytes for short names and limits length to 47 characters, but every student is one self-contained block. Copying a student is a plain assignment, sorting moves whole records with no pointers to fix up, and freeing the list is a single free. The average is computed once when a record is created, so sorting and printing never recompute it.

Records arrive as text lines in a simple CSV format: id,name,score,score,score, such as 1004,Maya Lopez,88,92,79. Real CSV allows quoted fields with commas inside; we'll keep it simple and forbid commas in names (a comma always separates fields), which the parser enforces automatically.

Stage 1: parse and store

Stage 1 reads lines from the Input box, turns each into a student, and keeps the valid ones. Most of the code is about validation, and that's realistic: in programs that read outside data, checking it usually takes more code than using it.

The dynamic array. list_push appends a record, doubling the capacity whenever the array is full (starting at 4), exactly as in Building a Dynamic Array. It uses realloc through a temporary pointer, so a failure leaves the list intact and the caller gets false. list_free releases the block and resets the struct to zero, so a freed list is a valid empty list again.

Splitting fields. parse_student copies the line into a local buffer (it must not modify the caller's text), then walks it with strchr, replacing each comma with '\0' so every field becomes its own string. We don't use strtok here because it treats consecutive commas as one separator, so an empty field, like the missing name in 1008,,80,80,80, would vanish and every field after it would shift one place to the left. Each field is trimmed of surrounding spaces, so 1001, Omar Haddad ,74,81,69 is accepted.

Checking values. parse_number wraps strtol with all the checks that function needs: something was parsed, nothing follows the number, no overflow, and the value is within a range. IDs must be 1 to 999999 and scores 0 to 100. The name must be non-empty and fit the array.

Reporting errors. Instead of printing directly, parse_student writes its reason into a buffer supplied by the caller (char *error, size_t error_size) with snprintf. That keeps the parser reusable: stage 3 calls the same function for typed commands and for lines read from a file, and each caller decides how to present the message.

C Stage 1: parse records into a dynamic array

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.

Five of the eleven lines are rejected, each with a specific reason: a missing score, a score of 105, an ID that isn't a number, a duplicate ID and an empty name. The six valid students end up in an array with capacity 8: it started at 4 and doubled once. The table uses printf field widths (%-16s pads the name to 16 characters, left-aligned; %7.2f right-aligns the average with two decimals) so the columns line up, as covered in Printing Output.

Note: The duplicate check uses list_find, a linear search. For a class of 30, that's instant. For a million records, checking every new record against all previous ones would be slow, and you'd keep an index such as a hash table keyed by ID instead.

Stage 2: sorting, statistics and searching

With the data in an array, qsort from <stdlib.h> can sort it in any order. It needs a comparator: a function that receives pointers to two elements and returns a negative number, zero or a positive number to say which comes first.

C
static int compare_by_id(const void *a, const void *b)
{
    const student *x = a;
    const student *y = b;
    return (x->id > y->id) - (x->id < y->id);
}

The expression (x > y) - (x < y) gives -1, 0 or 1 without the overflow risk of the tempting shortcut x->id - y->id, which is undefined behavior when the difference doesn't fit in an int. With IDs below a million it would happen to work, but the safe idiom costs nothing.

The other comparators show two more techniques. compare_by_name uses strcmp and, for equal names, falls back to the ID. compare_by_average sorts the highest average first by returning 1 when x is smaller, and breaks ties by name. Tie-breakers matter because qsort isn't stable: records that compare equal can come out in any order, and that order can change between C libraries. A complete ordering makes the output predictable everywhere.

print_stats walks the list once, collecting the sum of averages, the best student and a count per letter grade. The grade counter uses a small trick: strchr(grades, letter) - grades turns a letter into its index in the string "ABCDF".

Finally, bsearch finds a student by ID in logarithmic time, but only on an array sorted by the same key with the same comparator. That's why the program sorts by ID right before the lookups. The key passed to bsearch is a student with only the id filled in, because the comparator expects two pointers to the same type.

C Stage 2: sorting, statistics and bsearch

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.

Compare the two tables: in the ranking, Maya (86.33) comes before Ana (83.33) and the D student is last; alphabetically, Ana comes first. The lookup for 1010 reports "not found" because bsearch returns NULL when the key isn't present.

Stage 3: commands, saving and loading

The final stage turns the program into an interactive tool. Each line of input is a command:

Command Effect
add id,name,s1,s2,s3 Validate and add a student
list Print the table
sort id, sort name, sort average Sort the list
find id / remove id Look up or delete one student
save file / load file Write the list to a CSV file or replace it from one
stats Class statistics
clear Remove everyone

run_command splits the line into the command word and the rest (the argument) with strcspn, then dispatches with a chain of strcmp tests. For sort, the argument selects a comparator, stored in a function pointer variable and passed to qsort.

find now uses the linear list_find instead of bsearch, because the user can sort the list by any key at any moment, and bsearch would need it sorted by ID. Keeping a separate ID-sorted index is possible, but for a class-sized list the simple search is the right choice. remove closes the gap with memmove, which handles the overlapping source and destination correctly (memcpy would not), and keeps the remaining students in order.

Saving. save_file writes a comment header and one line per student with fprintf. It checks fopen and reports the reason with strerror(errno). At the end it checks both ferror and the return value of fclose. That matters because output is buffered: a full disk might only be noticed when fclose flushes the last block, and a program that ignores it would report success after losing data. See Error Handling.

Loading. load_file reads the file line by line with fgets, skips blank lines and # comments, and reuses parse_student, so a file is held to exactly the same rules as typed input. Errors include the file name and line number (class.csv:4: bad id 'x'), the format compilers use, which most editors can jump to.

Most importantly, loading is all or nothing. Records go into a new, temporary list, and only when the whole file has been read successfully does the function free the old list and replace it. If line 500 of a file is corrupt, the user keeps their current data rather than ending up with half a class. This "build aside, then swap" pattern is how careful programs update anything valuable.

C Stage 3: the complete records program

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.

The session in the Input box exercises every command. Two add lines are rejected (a duplicate ID and a missing score). After sort average, Lena leads. Omar is removed, the remaining three students are saved to class.csv, the list is cleared and shown empty, and load class.csv brings all three back, proving the file round trip works. Sorting by name and stats work on the loaded data, and loading a file that doesn't exist reports No such file or directory from strerror while keeping the current list.

Remember that files in our editor only exist during one run, so class.csv disappears when the program ends. On your own computer, the same program would leave a real file behind that you could open in a spreadsheet:

TEXT
# id,name,test1,test2,test3
1003,Lena Novak,95,89,97
1004,Maya Lopez,88,92,79
1002,Kenji Sato,62,70,58

Tip: Try breaking things. Add load class.csv before anything was saved, sort grade, find abc, remove 9999, or an add line with a 60-character name. Every one should produce a clear message and leave the data untouched.

Text or binary files?

We saved the records as text. The alternative is writing the structs directly with fwrite(list->items, sizeof list->items[0], list->count, file), one line of code that's faster and needs no parsing. The Binary Files lesson shows how. For this kind of data, text is usually the better choice:

Text (CSV) Binary (raw structs)
Readable and editable by people Yes No
Opens in spreadsheets and other tools Yes No
Portable between compilers and CPUs Yes No: padding, int size and byte order can differ
Needs parsing and validation code Yes Still needs validation if the file could be damaged
Speed and size Slower, larger Faster, compact

Binary formats shine for large data sets and fixed-layout records; the inventory project uses one.

Ideas to extend it

  • Edit a record with an update id,name,s1,s2,s3 command that replaces an existing student.
  • A variable number of tests: store scores in a flexible array member or a separate dynamic array, and write the count in the file header.
  • Quoted CSV fields so names may contain commas: 1010,"Lee, Ann",80,85,90.
  • Search by partial name with strstr, case-insensitively using tolower.
  • A histogram of averages with one row of # characters per grade.
  • Autosave: save to a backup file before clear or load, so nothing is ever lost by accident.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the comparator use (x->id > y->id) - (x->id < y->id) instead of x->id - y->id?

    qsort accepts any negative, zero or positive value, but the subtraction can overflow. The comparison idiom always produces -1, 0 or 1 safely.
  2. 2. What must be true before calling bsearch on the student array with compare_by_id?

    Binary search only works on data sorted by the key it searches, in the order its comparator defines.
  3. 3. Why does load_file read into a temporary list instead of directly into the current one?

    Only when the whole file is valid does it free the old list and replace it. A corrupt file can't leave the program with half the data.
  4. 4. Why check the return value of fclose after writing a file?

    Output is buffered; the final flush happens in fclose. Ignoring its result can turn lost data into a reported success.
  5. 5. Removing student 2 from an array of 5 is done with memmove rather than memcpy. Why?

    Shifting elements left by one copies a region onto an overlapping region. memcpy with overlap is undefined behavior.

Summary

  • Model one record as a struct; fixed-size name arrays keep each record self-contained, so copying and sorting are simple.
  • Keep records in a dynamic array that doubles its capacity with realloc through a temporary pointer.
  • Validate every field: split with strchr (not strtok, which merges empty fields), trim spaces, parse numbers with checked strtol, and report reasons through a caller-supplied buffer.
  • Sort with qsort and comparators that never overflow and break ties; search with bsearch only on data sorted by the same key.
  • Remove elements with memmove, which allows overlapping regions.
  • Save as CSV with fprintf and check ferror and fclose; load line by line into a temporary list and swap it in only when the whole file is valid.

Next: Project: Bank Account System