Skip to main content

Display records sorted by name from file

Short answer

Read name and roll from records.txt using fscanf into a struct array. Sort ascending by name with bubble sort using strcmp (swap whole struct when out of order). Print the sorted list.

Write the program to display the records in sorted order, sorting is performed in ascending order with respect to name using data files concept.

Logic. The records (name and roll) are stored in a text file records.txt, one record per line. The program reads them into an array of structures with fscanf(), sorts the array in ascending order of name with strcmp() (bubble sort, swapping whole structures) and displays them.

#include <stdio.h>
#include <string.h>
#define MAX 100

struct rec {
    char name[30];
    int roll;
};

int main(void)
{
    struct rec r[MAX], t;
    int n = 0;
    FILE *fp = fopen("records.txt", "r");

    if (fp == NULL) {
        printf("Cannot open records.txt\n");
        return 1;
    }
    while (n < MAX && fscanf(fp, "%29s %d", r[n].name, &r[n].roll) == 2)
        n++;
    fclose(fp);

    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - 1 - i; j++)
            if (strcmp(r[j].name, r[j + 1].name) > 0) {
                t = r[j]; r[j] = r[j + 1]; r[j + 1] = t;
            }

    printf("%-10s %s\n", "Name", "Roll");
    for (int i = 0; i < n; i++)
        printf("%-10s %d\n", r[i].name, r[i].roll);
    return 0;
}

Output (records.txt had the lines: Ram 1, Sita 2, Bibek 3, Hari 4, Anil 5)

Name       Roll
Anil       5
Bibek      3
Hari       4
Ram        1
Sita       2

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 10 questions →