luc085.c ​
Metadata ​
- Author — Amit Dutta
- Last updated — 08 Feb 2026
- License — MIT License (See the LICENSE file for details)
Problem Statement ​
Problem Statement
Suppose a file contains student records (Name, Age). Write a program to read these records and display them in sorted order by name.
Source Code ​
Printing the code
To print this file, open it on GitHub and click Raw before printing, or use the Download Raw button above and print directly from that page.
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct student
{
char name[40];
int age;
};
void create_dummy_data();
int compare_names(const void *a, const void *b);
int main()
{
FILE *fp;
struct student s[100];
int count = 0, i;
// Create sample file for demonstration
create_dummy_data();
fp = fopen("students.dat", "rb");
if (fp == NULL)
{
printf("Cannot open file!\n");
exit(1);
}
// Read records into array
while (fread(&s[count], sizeof(struct student), 1, fp) == 1)
{
count++;
}
fclose(fp);
// Sort the array
qsort(s, count, sizeof(struct student), compare_names);
printf("--- Student List (Sorted by Name) ---\n");
for (i = 0; i < count; i++)
{
printf("Name: %-20s Age: %d\n", s[i].name, s[i].age);
}
return 0;
}
int compare_names(const void *a, const void *b)
{
return strcmp(((struct student *)a)->name, ((struct student *)b)->name);
}
void create_dummy_data()
{
FILE *fp = fopen("students.dat", "wb");
struct student data[] = {
{"Zack", 20}, {"Alice", 19}, {"Bob", 21}, {"Charlie", 20}, {"Yasmine", 19}
};
if (fp)
{
fwrite(data, sizeof(struct student), 5, fp);
fclose(fp);
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66