luc085.c (1801B)
1 /* 2 * Author : Amit Dutta <amitdutta4255@gmail.com> 3 * Date : 08 Feb 2026 4 * Repo : https://github.com/notamitgamer/bsc 5 * License : MIT License (See the LICENSE file for details) 6 */ 7 8 /* Suppose a file contains student records (Name, Age). Write a program to read these records and display them in sorted order by name. 9 */ 10 /* Let Us C, Chap- 19 (File Input/Output), Qn No.: B(a) */ 11 12 /* This file is auto-generated by a bot. */ 13 /* This code is not compiled; it is for reference only. */ 14 15 16 #include <stdio.h> 17 #include <stdlib.h> 18 #include <string.h> 19 #include <ctype.h> 20 21 struct student 22 { 23 char name[40]; 24 int age; 25 }; 26 27 void create_dummy_data(); 28 int compare_names(const void *a, const void *b); 29 30 int main() 31 { 32 FILE *fp; 33 struct student s[100]; 34 int count = 0, i; 35 36 // Create sample file for demonstration 37 create_dummy_data(); 38 39 fp = fopen("students.dat", "rb"); 40 if (fp == NULL) 41 { 42 printf("Cannot open file!\n"); 43 exit(1); 44 } 45 46 // Read records into array 47 while (fread(&s[count], sizeof(struct student), 1, fp) == 1) 48 { 49 count++; 50 } 51 fclose(fp); 52 53 // Sort the array 54 qsort(s, count, sizeof(struct student), compare_names); 55 56 printf("--- Student List (Sorted by Name) ---\n"); 57 for (i = 0; i < count; i++) 58 { 59 printf("Name: %-20s Age: %d\n", s[i].name, s[i].age); 60 } 61 62 return 0; 63 } 64 65 int compare_names(const void *a, const void *b) 66 { 67 return strcmp(((struct student *)a)->name, ((struct student *)b)->name); 68 } 69 70 void create_dummy_data() 71 { 72 FILE *fp = fopen("students.dat", "wb"); 73 struct student data[] = { 74 {"Zack", 20}, {"Alice", 19}, {"Bob", 21}, {"Charlie", 20}, {"Yasmine", 19} 75 }; 76 if (fp) 77 { 78 fwrite(data, sizeof(struct student), 5, fp); 79 fclose(fp); 80 } 81 }