Monday, June 8, 2015

Block I/O fread/fwrite- file handling

#include<stdio.h>
#include<conio.h>
void main()
{
typedef struct student
{
char name[20];
int age;
}stu;
stu s1[10],s2;
int n,i;
FILE *fp1;
clrscr();
fp1=fopen("stud.dat","wb");
if(fp1==NULL)
{
printf("file creation error\n");
getch();
exit(1);
}
printf("enter the no of students\n");
scanf("%d",&n);
printf("entre the details of students\n");
for(i=0;i<n;i++)
{
printf("enter the name and age\n");
scanf("%s%d",s1[i].name,&s1[i].age);
}
fwrite(s1,sizeof(stu),n,fp1);
//fwrite(s1,sizeof(s1),1,fp1);
fclose(fp1);

fp1=fopen("stud.dat","rb");
if(fp1==NULL)
{
printf("file does not exist\n");
getch();
exit(1);
}
else
{
//reading 1 record at a time from file
while(fread(&s2,sizeof(s2),1,fp1)==1)
{
printf("\nname->%s age->%d",s2.name,s2.age);
}
//reading all n records at once from file
fread(s1,sizeof(stu),n,fp1);
for(i=0;i<n;i++)
{
printf("\nname->%s age->%d",s1[i].name,s1[i].age);
}
}
fclose(fp1);
getch();
}

No comments:

Post a Comment