File Handling using a Binary file to write a structure variable to a file and read the same to display it as output.
Language : C
[sourcecode language='c']
#include
#include
void write();
void read();
struct employee
{
int no, sal;
char gen, name[20];
};
void main()
{ int a;
printf(” 1. Creating the Employee File\n 2.Reading Employee File : “);
scanf(“%d”,&a);
switch(a)
{
case 1:
write();
break;
case 2:
read();
break;
default :
printf(“Invalid Choice!”);
}
}
void write()
{ int i,n;
struct employee e;
FILE *fp;
fp=fopen(“Employee.dat”, “wb”);
if(fp==NULL)
{
printf(“File Creation Failed!”);
exit(0);
}
printf(“Enter the nos. of employees : “);
scanf(“%d”, &n);
for(i=0;i
printf(“Enter the Employee Number : “);
scanf(“%d”, &e.no);
printf(“Enter the Employee Salary : “);
scanf(“%d”, &e.sal);
printf(“Enter the Employee gender: “);
fflush(stdin);
scanf(“%c”, &e.gen);
printf(“Enter the Employee Name : “);
fflush(stdin);
gets(e.name);
printf(“\n\n”);
fwrite((char *)&e, sizeof(e), 1, fp);
}
fclose(fp);
}
void read()
{ struct employee e;
FILE *fp;
fp=fopen(“Employee.dat”, “rb”);
if(fp==NULL)
{
printf(“\n\tFile doesn’t exist!!!\TRY AGAIN”);
exit(0);
}
while((fread((char *)&e, sizeof(e), 1, fp))==1)
{
printf(“\nEmployee Number : %d”, e.no);
printf(“\nEmployee Salary : %d”, e.sal);
printf(“\nEmployee gender : %c”,e.gen);
printf(“\nEmployee Name : %s”,e.name);
printf(“\n\n”);
}
fclose(fp);
}
[/sourcecode]






