- 2072 Kartik · 6 marks
Write student records to STUDENT.DAT
Short answer
Method: Open "STUDENT.DAT" in write mode ("w"). Loop 5 times: read name, roll, age; write each record as a text line with fprintf. Result: File contains five lines, each with name, roll number, and age.
Write a program to write name, roll no and age of five students into a disk file name "STUDENT.DAT".
Logic. A text file STUDENT.DAT is opened in write mode (the opening is checked for NULL). A loop of five repetitions reads name, roll number and age, and fprintf() writes them as one line in the file.
#include <stdio.h>
int main(void)
{
FILE *fp;
char name[30];
int roll, age;
fp = fopen("STUDENT.DAT", "w");
if (fp == NULL) {
printf("Cannot open STUDENT.DAT\n");
return 1;
}
for (int i = 1; i <= 5; i++) {
printf("Student %d (name roll age): ", i);
scanf("%29s %d %d", name, &roll, &age);
fprintf(fp, "%s %d %d\n", name, roll, age);
}
fclose(fp);
printf("Records written to STUDENT.DAT\n");
return 0;
}
Sample run
Input: Ram 1 19 Sita 2 18 Hari 3 20 Gita 4 19 Bibek 5 21
Student 1 (name roll age): Student 2 (name roll age): Student 3 (name roll age): Student 4 (name roll age): Student 5 (name roll age): Records written to STUDENT.DAT
STUDENT.DAT afterwards contains the lines:
Ram 1 19
Sita 2 18
Hari 3 20
Gita 4 19
Bibek 5 21
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Display records sorted by name from file · Computer Programming, chapter 10
- Student records with two functions · Computer Programming, chapter 8
- Pass student array; display passed students · Computer Programming, chapter 7
- Binary file of 48 students; highest mark · Computer Programming, chapter 10
- Store 48 students in file with append · Computer Programming, chapter 10
- 96 students record; pass marks · Computer Programming, chapter 10
- Student records file with CRN search · Object Oriented Programming, chapter 8
- File stream; student binary file program · 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