Skip to main content

Binary file of 48 students; highest mark

Short answer

Define struct student with name, roll, address, mark. Input 48 records, write to binary file student.dat with fwrite. Reopen for reading, read with fread, track the record with maximum mark, then display that student’s details.

Write a program to input and save record like name, roll, address and obtained mark of 48 students in a binary file and search and display the record of a student whose obtained mark in highest. The information should be organized in a structure.

Design. The structure student holds name, roll, address and mark. All 48 records are written to the binary file student.dat with fwrite(). The file is reopened with "rb" and records are read one by one with fread(); the record with the highest mark is kept in top (the first record starts it). That record is displayed at the end.

#include <stdio.h>
#ifndef N
#define N 48
#endif

struct student {
    char name[30];
    int roll;
    char address[30];
    float mark;
};

int main(void)
{
    FILE *fp;
    struct student s, top;
    int first = 1;

    fp = fopen("student.dat", "wb");
    if (fp == NULL) { printf("Cannot open file\n"); return 1; }
    for (int i = 1; i <= N; i++) {
        printf("Student %d (name roll address mark): ", i);
        scanf("%29s %d %29s %f", s.name, &s.roll, s.address, &s.mark);
        fwrite(&s, sizeof s, 1, fp);
    }
    fclose(fp);

    fp = fopen("student.dat", "rb");
    if (fp == NULL) { printf("Cannot open file\n"); return 1; }
    while (fread(&s, sizeof s, 1, fp) == 1)
        if (first || s.mark > top.mark) {
            top = s;
            first = 0;
        }
    fclose(fp);

    printf("Highest mark: %s, Roll %d, %s, %.1f\n", top.name, top.roll, top.address, top.mark);
    return 0;
}

Sample run (N reduced to 3 with -DN=3 for the test; the real program uses 48)

Input: Ram 1 Lalitpur 65 Sita 2 Kathmandu 88.5 Hari 3 Pokhara 72

Student 1 (name roll address mark): Student 2 (name roll address mark): Student 3 (name roll address mark): Highest mark: Sita, Roll 2, Kathmandu, 88.5

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 10 questions →