luc085.c¶
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.
Metadata¶
| Property | Detail |
|---|---|
| Author | Amit Dutta amitdutta4255@gmail.com |
| Date | 08 Feb 2026 |
| License | MIT License (See the LICENSE file for details) |
Actions¶
💡 You can print or save this file by opening Raw and using your browser.
Source Code¶
#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);
}
}