#include <stdio.h>

typedef struct {
    char name[50];
    int roll_no;
    char grade;
    char branch[50];
} Student;

void write_student_records(const char filename[], Student students[], int n) {
    FILE *file = fopen(filename, "w");
    if (file == NULL) {
        printf("Error opening file.\n");
        return;
    }

    for (int i = 0; i < n; i++) {
        fprintf(file, "%s %d %c %s\n", students[i].name, students[i].roll_no, students[i].grade, students[i].branch);
    }

    fclose(file);
}

void store_branchwise_records(const char filename[]) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        return;
    }

    Student student;
    char branch_filename[50];

    while (fscanf(file, "%s %d %c %s", student.name, &student.roll_no, &student.grade, student.branch) != EOF) {
        sprintf(branch_filename, "%s.txt", student.branch);
        FILE *branch_file = fopen(branch_filename, "a");
        if (branch_file == NULL) {
            printf("Error opening branch file.\n");
            continue;
        }
        fprintf(branch_file, "%s %d %c\n", student.name, student.roll_no, student.grade);
        fclose(branch_file);
    }

    fclose(file);
}

int main() {
    int n;
    printf("Enter the number of students: ");
    scanf("%d", &n);

    Student students[n];

    for (int i = 0; i < n; i++) {
        printf("Enter details for student %d:\n", i + 1);
        printf("Name: ");
        scanf("%s", students[i].name);
        printf("Roll No: ");
        scanf("%d", &students[i].roll_no);
        printf("Grade: ");
        scanf(" %c", &students[i].grade);
        printf("Branch: ");
        scanf("%s", students[i].branch);
    }

    write_student_records("students.txt", students, n);
    store_branchwise_records("students.txt");

    printf("Records stored branch-wise in separate files.\n");

    return 0;
}
