Monday 23 February 2015

Reading & Writing Records To The File in C


/*  Reading & Writing Records To The File  */

#include<stdio.h>
#include<conio.h>

struct Student
{
int Eno;
char Name[50];
};

main()
{
int n,i=0;

FILE *p;

struct Student S1,S2;

clrscr();

p=fopen("A.txt","wb");

printf("\n How Many Records    ?\n");
scanf("%d",&n);

while(i<n)
{
printf("\n Enter Your Enrollment No  :");
scanf("%d",&S1.Eno);
printf("\n Enter Your Name  :");
fflush(stdin);
gets(S1.Name);
fwrite(&S1,sizeof(S1),1,p);
i++;
}
fclose(p);

p=fopen("A.txt","rb");

printf("\n File Contents\n");

while((fread(&S2,sizeof(S2),1,p))!=NULL)
{
printf("\n File Pointer Position :%d",ftell(p));
printf("\n Your Enrollment No   :%d",S2.Eno);
printf("\n Enter Your Name       :%s",S2.Name);
}

rewind(p);
printf("\n\n\n");
while((fread(&S2,sizeof(S2),1,p))!=NULL)
{
printf("\n File Pointer Position :%d",ftell(p));
printf("\n Your Enrollment No   :%d",S2.Eno);
printf("\n Enter Your Name       :%s",S2.Name);
}
rewind(p);
printf("\n\n\n");

fseek(p,104L,1);

fread(&S2,sizeof(S2),1,p);
printf("\n Your Enrollment No   :%d",S2.Eno);
printf("\n Enter Your Name       :%s",S2.Name);

getch();
}

No comments:

Post a Comment