Q : Write a program to write records of students in a file, where each record consists of student name, roll number, CGPA, and address. Read the records back from the file and display them.
#include<stdio.h>
#include<conio.h>
/*============================
Girfa Student Help
Structure write back to file
==============================*/
struct stu
{
char name[20];
int roll;
int cgpa;
char add[20];
};
void main()
{
FILE *ft;
struct stu ob;
int r,i;
clrscr();
ft=fopen("test.txt","w");
if(ft==NULL)
puts("Output
file opening error");
else
{
printf("How
many record you want to enter>> ");
scanf("%d",&r);
for(i=1;i<=r;i++)
{
fflush(stdin);
printf("\nEnter name for %d record>> ",i);
gets(ob.name);
printf("Enter roll for %d record>> ",i);
scanf("%d",&ob.roll);
printf("Enter CGPA for %d record>> ",i);
scanf("%d",&ob.cgpa);
fflush(stdin);
printf("Enter address for %d record>> ",i);
gets(ob.add);
fwrite(&ob,sizeof(ob),1,ft);
}
fclose(ft);
ft=fopen("test.txt","rb");
clrscr();
while(fread(&ob,sizeof(ob),1,ft)==1)
{
printf("\n\nName=%s",ob.name);
printf("\nRoll=%d",ob.roll);
printf("\nCGPA=%d",ob.cgpa);
printf("\nAddress=%s",ob.add);
}
}
getch();
}
No comments:
Post a Comment