#include <stdio.h>
int main() {
// Open the file in write mode.
FILE *fptr = fopen("score.dat", "w");
if (fptr == NULL) {
printf("Error opening file.\n");
return 1;
}
// Prompt the user for the student's information.
char name[50];
int reg_no;
char gender[10];
char address[100];
do {
printf("Enter the student's name: ");
fgets(name, 50, stdin);
name[strlen(name) - 1] = '\0';
printf("Enter the student's registration number: ");
scanf("%d", ®_no);
printf("Enter the student's gender (M/F): ");
fgets(gender, 10, stdin);
gender[strlen(gender) - 1] = '\0';
printf("Enter the student's address: ");
fgets(address, 100, stdin);
address[strlen(address) - 1] = '\0';
// Write the student's information to the file.
fprintf(fptr, "%d %s %s %s\n", reg_no, name, gender, address);
printf("Do you want to continue (Y/N)? ");
char ch;
fgets(&ch, 1, stdin);
ch = toupper(ch);
} while (ch == 'Y');
// Close the file.
fclose(fptr);
// Display all the records in the file.
fptr = fopen("score.dat", "r");
if (fptr == NULL) {
printf("Error opening file.\n");
return 1;
}
while (!feof(fptr)) {
char line[100];
fgets(line, 100, fptr);
printf("%s\n", line);
}
// Close the file.
fclose(fptr);
return 0;
}C Program to create a data file named score.dat to store students’ information with Reg_no, name, gender, and address. The program should ask the user to continue or not. When finished, the program should also display all the records in the proper format.
Student Information File Management in C
A free online educational resource provider.