luc093.c¶
Problem Statement
Update Master file (Roll, Name) using Transaction file (Roll, Code Add/Delete). Both files are sorted by Roll.
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 student {
int roll;
char name[30];
};
struct trans {
int roll;
char code; // 'A' for Add, 'D' for Delete
char name[30]; // Only needed for Add
};
void create_files();
int main()
{
FILE *fm, *ft, *fn;
struct student m;
struct trans t;
int has_m, has_t;
create_files();
fm = fopen("MASTER.DAT", "rb");
ft = fopen("TRANS_ROLL.DAT", "rb");
fn = fopen("NEW_MASTER.DAT", "wb");
if (!fm || !ft || !fn) exit(1);
has_m = fread(&m, sizeof(struct student), 1, fm);
has_t = fread(&t, sizeof(struct trans), 1, ft);
printf("Merging Master and Transaction files...\n");
while (has_m && has_t)
{
if (m.roll < t.roll)
{
// No transaction for this master record, keep it
fwrite(&m, sizeof(struct student), 1, fn);
has_m = fread(&m, sizeof(struct student), 1, fm);
}
else if (m.roll == t.roll)
{
// Transaction affects this record
if (t.code == 'D')
{
printf("Deleting Roll %d\n", m.roll);
// Skip writing 'm' to file (Deleting)
has_m = fread(&m, sizeof(struct student), 1, fm);
}
else
{
// Logic error: Can't ADD if ID exists. Maybe Update?
// Assuming replace or skip. Let's skip T and keep M for now.
has_m = fread(&m, sizeof(struct student), 1, fm);
}
has_t = fread(&t, sizeof(struct trans), 1, ft);
}
else // m.roll > t.roll
{
// Transaction ID is new
if (t.code == 'A')
{
struct student new_s;
new_s.roll = t.roll;
strcpy(new_s.name, t.name);
fwrite(&new_s, sizeof(struct student), 1, fn);
printf("Adding Roll %d\n", new_s.roll);
}
has_t = fread(&t, sizeof(struct trans), 1, ft);
}
}
// Process remaining Master
while (has_m)
{
fwrite(&m, sizeof(struct student), 1, fn);
has_m = fread(&m, sizeof(struct student), 1, fm);
}
// Process remaining Transactions (Only Adds)
while (has_t)
{
if (t.code == 'A')
{
struct student new_s = {t.roll, ""};
strcpy(new_s.name, t.name);
fwrite(&new_s, sizeof(struct student), 1, fn);
printf("Adding Roll %d\n", new_s.roll);
}
has_t = fread(&t, sizeof(struct trans), 1, ft);
}
fclose(fm); fclose(ft); fclose(fn);
return 0;
}
void create_files()
{
struct student m[] = {{10, "A"}, {20, "B"}, {30, "C"}};
struct trans t[] = {{15, 'A', "NewGuy"}, {20, 'D', ""}, {40, 'A', "LastGuy"}};
FILE *f1 = fopen("MASTER.DAT", "wb");
fwrite(m, sizeof(struct student), 3, f1);
fclose(f1);
FILE *f2 = fopen("TRANS_ROLL.DAT", "wb");
fwrite(t, sizeof(struct trans), 3, f2);
fclose(f2);
}