Skip to main content

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)

All Computer Programming chapter 10 questions →