Skip to main content

Store 48 students in file with append

Short answer

Open file in append mode "a" (creates if missing). Loop 48 times: read name and roll number; write with fprintf. Result: New records are added at the end without deleting existing content.

Write a program to read name and roll number of 48 students from user and store them in file. If the file already contains data, your program should add new data at the end of the file.

Key point. The file is opened in append mode "a". If the file already has data, new data is written after the existing data (the old data is kept); if the file does not exist it is created. Mode "w" would erase the old content.

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

int main(void)
{
    FILE *fp;
    char name[30];
    int roll;

    fp = fopen("students.txt", "a");     /* "a": append, creates file if absent */
    if (fp == NULL) {
        printf("Cannot open file\n");
        return 1;
    }
    for (int i = 1; i <= N; i++) {
        printf("Student %d (name roll): ", i);
        scanf("%29s %d", name, &roll);
        fprintf(fp, "%s %d\n", name, roll);
    }
    fclose(fp);
    printf("%d records added\n", N);
    return 0;
}

Sample run (N reduced to 3 for the test with -DN=3; the file already had the line "Old 100")

Input: Ram 1 Sita 2 Hari 3

Student 1 (name roll): Student 2 (name roll): Student 3 (name roll): 3 records added

The file contents afterwards: Old 100, Ram 1, Sita 2, Hari 3. With the real N = 48 the loop simply runs 48 times.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 10 questions →