luc090.c¶
Problem Statement
Read employee records (code, name, date, salary), sort them by Date of Joining, and write to a target file.
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 date { int d, m, y; };
struct employee {
int empcode[6]; // Not used as int array usually, likely int id. Assuming int code.
char empname[20];
struct date join_date;
float salary;
};
// Redefining struct for easier usage assuming empcode is int
struct emp_clean {
int code;
char name[20];
struct date doj;
float salary;
};
void create_emp_file();
int compare_dates(const void *a, const void *b);
int main()
{
FILE *fp, *ft;
struct emp_clean e[50];
int count = 0, i;
create_emp_file();
fp = fopen("employee.dat", "rb");
if (!fp) return 1;
while (fread(&e[count], sizeof(struct emp_clean), 1, fp) == 1)
count++;
fclose(fp);
qsort(e, count, sizeof(struct emp_clean), compare_dates);
ft = fopen("emp_sorted.dat", "wb");
fwrite(e, sizeof(struct emp_clean), count, ft);
fclose(ft);
printf("Sorted records written to 'emp_sorted.dat'.\nDisplaying sorted list:\n");
for(i=0; i<count; i++)
printf("%s - %02d/%02d/%04d\n", e[i].name, e[i].doj.d, e[i].doj.m, e[i].doj.y);
return 0;
}
int compare_dates(const void *a, const void *b)
{
struct emp_clean *e1 = (struct emp_clean *)a;
struct emp_clean *e2 = (struct emp_clean *)b;
if (e1->doj.y != e2->doj.y) return e1->doj.y - e2->doj.y;
if (e1->doj.m != e2->doj.m) return e1->doj.m - e2->doj.m;
return e1->doj.d - e2->doj.d;
}
void create_emp_file()
{
struct emp_clean data[] = {
{1, "John", {12, 5, 2022}, 5000},
{2, "Jane", {10, 1, 2020}, 6000}, // Senior
{3, "Bob", {15, 8, 2021}, 5500}
};
FILE *f = fopen("employee.dat", "wb");
fwrite(data, sizeof(struct emp_clean), 3, f);
fclose(f);
}