/* * Author : Amit Dutta * Date : 08 Feb 2026 * Repo : https://github.com/notamitgamer/bsc * License : MIT License (See the LICENSE file for details) */ /* Suppose a file contains student records (Name, Age). Write a program to read these records and display them in sorted order by name. */ /* Let Us C, Chap- 19 (File Input/Output), Qn No.: B(a) */ /* This file is auto-generated by a bot. */ /* This code is not compiled; it is for reference only. */ #include #include #include #include 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); } }