Home » Sometech » Define a structure with the following elements int roll; char name[20]; float marks[3]; char grade; Write a program to write the students record in a file and then read this file to display the record of a particular student.

Define a structure with the following elements int roll; char name[20]; float marks[3]; char grade; Write a program to write the students record in a file and then read this file to display the record of a particular student.

#include<stdio.h>

void main()

{

FILE * fptr;

struct student

{

 int roll; 

 char name[20];

 float marks[3];

 char grade;

};

 

struct student stud;

int i,n,j,size,rl,flag=0;

float total,avg;

clrscr();

fptr=fopen(“studrecord.dat”,”w”);

if(!fptr)

 printf(“\n can not open target file for writing…”);

else

{

  size=sizeof(stud);

printf(“How many students are there? “);

scanf(“%d”,&n);

for(i=1;i<=n;i++)

{

 fflush(stdin); //empty the input buffer;

 printf(“\nEnter the data for student %d “,i);

 printf(“\nRoll number : “);

 

scanf(“%d”,&stud.roll);

 fflush(stdin); //empty the input buffer;

 printf(“\nName      :”);

 gets(stud.name);

 total=0;

 for(j=0;j<3;j++)

 {

   printf(“Marks %d :”,j+1);

   scanf(“%f”,&stud.marks[j]);

   total=total+stud.marks[j];

 }

avg=total/3.0;

if(avg>=75)

 stud.grade=’A’;

else if(avg>=50)

      stud.grade=’B’;

     else

             stud.grade=’C’;

 fwrite(&stud,size,1,fptr);//write the record to file

}

}

printf(“\nAll the records are stored into file…”);

fclose(fptr);

fptr=fopen(“studrecord.dat”,”r”);

if(!fptr)

 printf(“\n can not open source file for reading…”);

else

{

  printf(“\nEnter the roll number to see the record : “);

  scanf(“%d”,&rl);

while(fread(&stud,size,1,fptr))

{

 if(rl==stud.roll)

  {

  flag=1;

  printf(“\nRoll Number : %d”,rl);

printf(“\nName        : %s”,stud.name);

  printf(“\nMarks1      : %.2f”,stud.marks[0]);

  printf(“\nMarks2      : %.2f”,stud.marks[1]);

  printf(“\nMarks3      : %.2f”,stud.marks[2]);

  printf(“\nGrade       : %c”,stud.grade);

   }

}

if(flag==0)

 printf(“\nNo such roll number exist in the file”);

}

getch();

}

Advertisements

SoME Tech

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

%d bloggers like this: