Here is another example of File
Operation with fread() and fwrite().
#include <stdio.h>
#include <conio.h>
#include <dos.h>
struct
empl
{
char
name[30];
float
sal;
struct
{int dd,mm,yy;}db,rd;
}em,*emp;
int
c;
int
d1[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int
pr(int c)
{
FILE *fp;
int y,m,d,y1;
int
count=0;
struct
date dts;
getdate(&dts);
fp=fopen("emp.txt","r");
if(c==1)
{
printf("\n-----------------------------------------------------------------------------");
printf("\n Employee Salary Date of
Date of Years Left");
printf("\n Name Birth Retirment For Retirement");
printf("\n-----------------------------------------------------------------------------");
}
while(fread(&em,sizeof(em),1,fp)==1)
{
if(c==0)
count++;
else
{
printf("\n %-20s %8.2f %2d-%2d-%4d %2d-%2d-%4d
",em.name,em.sal,em.db.dd,em.db.mm,em.db.yy,em.rd.dd,em.rd.mm,em.rd.yy);
y=em.rd.yy-em.db.yy;
m=em.rd.mm-em.db.mm;
d=em.rd.dd-em.db.dd;
if(m<0)
{
y=y-1;
m=12-m;
}
if(d<0)
{
m=m-1;
d=m[d1]-em.db.dd;
}
y1=(em.rd.yy-em.db.yy)-(dts.da_year-em.db.yy);
printf(" %d",y1);
}
}
if(c==1)
{
printf("\n-----------------------------------------------------------------------------");
}
return
count;
}
void write()
{
FILE *fp;
// c=pr(c);
fp=fopen("emp.txt","a");
fflush(stdin);
printf("\n\t\tEnter
Emplyee Name : ");
gets(em.name);
printf("\n\t\tEnter
Emplyee Salary : ");
scanf("%f",&em.sal);
printf("\n\t\tEnter
Emplyee Date of Birth (dd mm yyyy) : ");
scanf("%d",&em.db.dd);
scanf("%d",&em.db.mm);
scanf("%d",&em.db.yy);
printf("\n\t\tEnter
Emplyee Date of Retirement (dd mm yyyy) : ");
scanf("%d",&em.rd.dd);
scanf("%d",&em.rd.mm);
scanf("%d",&em.rd.yy);
fwrite(&em,sizeof(em),1,fp);
fclose(fp);
}
void
sort()
{
FILE
*fp;
int
i,j;
struct
empl emp1;
c=pr(0);
emp=(struct
empl *)malloc(sizeof(c));
fp=fopen("emp.txt","r");
i=0;
while(fread(&em,sizeof(em),1,fp)==1)
{
emp[i]=em;
i++;
}
fclose(fp);
for(i=0;i<c-1;i++)
{
for(j=i+1;j<c;j++)
{
if(emp[i].sal>emp[j].sal)
{
emp1=emp[i];
emp[i]=emp[j];
emp[j]=emp1;
}
}
}
fp=fopen("emp.txt","w");
i=0;
while(i<c)
{
em=emp[i];
fwrite(&em,sizeof(em),1,fp);
i++;
}
fclose(fp);
}
void
main()
{
int
cn=0;
clrscr();
while(cn<4)
{
printf("\n\n\n\n\t1. Write\n\t2.
Print\n\t3. Sort\n\t4. Exit");
printf("\n\tEnter a Choice : ");
scanf("%d",&cn);
switch(cn)
{
case
1:write();break;
case
2:pr(1);break;
case
3:sort();printf("\nAfter Sort\n");pr(1);break;
}
}
getch();
}
No comments:
Post a Comment