- 2073 Shrawan · 6 marks
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)
Related questions
- Binary file of 48 students; highest mark · Computer Programming, chapter 10
- Read records until end; show nth record · Computer Programming, chapter 10 · asked 2×
- 96 students record; pass marks · Computer Programming, chapter 10
- Display records sorted by name from file · Computer Programming, chapter 10
- INVENTORY file of items · Computer Programming, chapter 10
- Employee text file; sort into binary file · Computer Programming, chapter 10
- Student file read/write and modify by roll · Object Oriented Programming, chapter 8
- File stream; student binary file program · Object Oriented Programming, chapter 8
- Muster roll for user's committee project · Construction Management, chapter 8
- Student records file with CRN search · Object Oriented Programming, chapter 8