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