- 2068 Chaitra · 8 marks
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)
Related questions
- Pass student array; display passed students · Computer Programming, chapter 7
- 96 students record; pass marks · Computer Programming, chapter 10
- Store 48 students in file with append · Computer Programming, chapter 10
- Display records sorted by name from file · Computer Programming, chapter 10
- Employee text file; sort into binary file · Computer Programming, chapter 10
- Student records with two functions · Computer Programming, chapter 8
- File stream; student binary file program · Object Oriented Programming, chapter 8
- Student records file with CRN search · Object Oriented Programming, chapter 8
- Student file read/write and modify by roll · Object Oriented Programming, chapter 8
- Student file displayed in descending marks order · Object Oriented Programming, chapter 8