Write a program which writes student name, registration number, semester, section
and CGPA of a student in a file entitled “student.dat” using structure. Repeat file
writing for as much number of students as user want.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student{
char name[30];
char registrationNumber[30];
int semester;
char section[30];
float CGPA;
};
void saveStudentsToFile(struct student students[],int totalStudents);
//The start point of the program
int main( void){
struct student students[100];
int totalStudents=0;
int totalTestPercentages=0;
int exit=1;
FILE *infile;
struct student input;
// Open students.dat for reading
infile = fopen ("students.dat", "r");
if (infile != NULL)
{
printf ("%-20s%-20s%-20s%-20s%-20s\n", "Name", "Reg. Number","Semester","Section", "CGPA");
// read file contents till end of file
while(fread(&input, sizeof(struct student), 1, infile)){
printf ("%-20s%-20s%-20d%-20s%-20.1f\n", input.name, input.registrationNumber, input.semester, input.section, input.CGPA);
}
// close file
fclose (infile);
}
while(exit==1){
printf("Enter a student name: ");
gets(students[totalStudents].name);
printf("Enter a student registration number: ");
gets(students[totalStudents].registrationNumber);
printf("Enter a student semester: ");
scanf("%d",&students[totalStudents].semester);
fflush(stdin);
printf("Enter a student section: ");
gets(students[totalStudents].section);
printf("Enter a student CGPA: ");
scanf("%f",&students[totalStudents].CGPA);
totalStudents++;
printf("Do you want to add a new student? 1 - yes, 0 - no: ");
scanf("%d",&exit);
fflush(stdin);
}
saveStudentsToFile(students,totalStudents);
getchar();
getchar();
return 0;
}
void saveStudentsToFile(struct student students[],int totalStudents){
FILE *outStudentsFile;
int i=0;
// open file for writing
outStudentsFile = fopen ("students.dat", "w");
// write struct to file
for(i=0;i<totalStudents;i++){
fwrite (&students[i], sizeof(struct student),1, outStudentsFile);
}
// close file
fclose (outStudentsFile);
}
Comments
Leave a comment