luc090.c (2269B)
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 /* Read employee records (code, name, date, salary), sort them by Date of Joining, and write to a target file. 9 */ 10 /* Let Us C, Chap- 19 (File Input/Output), Qn No.: B(f) */ 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 date { int d, m, y; }; 22 struct employee { 23 int empcode[6]; // Not used as int array usually, likely int id. Assuming int code. 24 char empname[20]; 25 struct date join_date; 26 float salary; 27 }; 28 29 // Redefining struct for easier usage assuming empcode is int 30 struct emp_clean { 31 int code; 32 char name[20]; 33 struct date doj; 34 float salary; 35 }; 36 37 void create_emp_file(); 38 int compare_dates(const void *a, const void *b); 39 40 int main() 41 { 42 FILE *fp, *ft; 43 struct emp_clean e[50]; 44 int count = 0, i; 45 46 create_emp_file(); 47 48 fp = fopen("employee.dat", "rb"); 49 if (!fp) return 1; 50 51 while (fread(&e[count], sizeof(struct emp_clean), 1, fp) == 1) 52 count++; 53 fclose(fp); 54 55 qsort(e, count, sizeof(struct emp_clean), compare_dates); 56 57 ft = fopen("emp_sorted.dat", "wb"); 58 fwrite(e, sizeof(struct emp_clean), count, ft); 59 fclose(ft); 60 61 printf("Sorted records written to 'emp_sorted.dat'.\nDisplaying sorted list:\n"); 62 for(i=0; i<count; i++) 63 printf("%s - %02d/%02d/%04d\n", e[i].name, e[i].doj.d, e[i].doj.m, e[i].doj.y); 64 65 return 0; 66 } 67 68 int compare_dates(const void *a, const void *b) 69 { 70 struct emp_clean *e1 = (struct emp_clean *)a; 71 struct emp_clean *e2 = (struct emp_clean *)b; 72 73 if (e1->doj.y != e2->doj.y) return e1->doj.y - e2->doj.y; 74 if (e1->doj.m != e2->doj.m) return e1->doj.m - e2->doj.m; 75 return e1->doj.d - e2->doj.d; 76 } 77 78 void create_emp_file() 79 { 80 struct emp_clean data[] = { 81 {1, "John", {12, 5, 2022}, 5000}, 82 {2, "Jane", {10, 1, 2020}, 6000}, // Senior 83 {3, "Bob", {15, 8, 2021}, 5500} 84 }; 85 FILE *f = fopen("employee.dat", "wb"); 86 fwrite(data, sizeof(struct emp_clean), 3, f); 87 fclose(f); 88 }