Q. Write a C code to keep record of n number of family members using structure and write to a FILE and read from it and display on console.
OR
Q. Write a C program to write any members of structure to a file using fwrite(). Read the contents from the file using fread() and display on the screen.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct family
{
char name[30];
int age;
};
void main()
{
struct family *f1,*f2;
int i,n;
FILE *fptr;
fptr=fopen("D:\\sentence.txt","wb");
printf("Enter number of family members: ");
scanf("%d",&n);
f1=(struct family*)malloc(n*sizeof(struct family));
f2=(struct family*)malloc(n*sizeof(struct family));
for(i=0;i<n;i++)
{
fflush(stdin);
printf("\nFor member %d",i+1);
printf("\nEnter name: ");
gets(f1->name);
printf("Enter age: ");
scanf("%d",&f1->age);
fwrite(f1,sizeof(struct family),1,fptr);
}
fclose(fptr);
fptr=fopen("D:\\sentence.txt","rb");
if(fptr==NULL)
{
printf("File could not be opened");
exit(1);
}
printf("\n\nDisplaying from the FILE:");
for(i=0;i<n;i++)
{
fread(f2,sizeof(struct family),1,fptr);
printf("\nName: %s\tAge: %d",f2->name,f2->age);
}
fclose(fptr);
getch();
}
No comments:
Post a Comment