Example
of Write, Read, modify and
delete.
//Write, Read,
modify and delete
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct emp
{
char
name[30];
int
days,wages,sal;
}emp;
void
add()
{
FILE
*fptr;
fptr=fopen("emp.txt","w");
printf("\n\tEmployee
Name:");
fflush(stdin);
gets(emp.name);
fflush(stdin);
printf("\n\tDays
Worked : ");
scanf("%d",&emp.days);
printf("\n\tWages
: ");
scanf("%d",&emp.wages);
emp.sal=emp.days*emp.wages;
fwrite(&emp,sizeof(emp),1,fptr);
fclose(fptr);
}
void
disp()
{
FILE
*fptr;
fptr=fopen("emp.txt","r");
printf("\n\n\t
Employee\t\t\tDays\tWage\tSalary");
printf("\n\t Name");
printf("\n\t======================================================");
while(fread(&emp,sizeof(emp),1,fptr)==1)
{
printf("\n\t
%-30s\t %d\t %d\t %d",emp.name,emp.days, emp.wages, emp.sal);
}
printf("\n\t======================================================");
}
void
modify()
{
char
name[20];
FILE
*fptr,*fptr1;
int
flag=0;
fptr=fopen("emp.txt","r");
fptr1=fopen("temp.txt","w");
printf("\n\tEnter
Employee Name to Modify: ");
fflush(stdin);
gets(name);
fflush(stdin);
while(fread(&emp,sizeof(emp),1,fptr)==1)
{
if(stricmp(emp.name,name)==0)
{
flag=1;
printf("\n\tEnter
New Days & Wage:");
scanf("%d%d",&emp.days,&emp.wages);
emp.sal=emp.days*emp.wages;
}
fwrite(&emp,sizeof(emp),1,fptr1);
}
if(flag==1)
{
printf("\n\tThe
Profile is Modified");
}
else
{
printf("\n\tRecord
is Not Found!!");
}
fclose(fptr);
fclose(fptr1);
remove("emp.txt");
rename("temp.txt","emp.txt");
}
void
del ()
{
char
name[20];
FILE
*fptr,*fptr1;
int
flag=0;
fptr=fopen("emp.txt","r");
fptr1=fopen("temp.txt","w");
printf("\n\tEnter
Employee Name to Delete : ");
fflush(stdin);
gets(name);
fflush(stdin);
while(fread(&emp,sizeof(emp),1,fptr)==1)
{
if(stricmp(emp.name,name)!=0)
{
fwrite(&emp,sizeof(emp),1,fptr1);
}
else
{
flag=1;
}
}
if(flag==1)
{
printf("\n\tThe
Profile is Deleted");
}
else
{
printf("\n\tRecord
is Not Found!!");
}
fclose(fptr);
fclose(fptr1);
remove("emp.txt");
rename("temp.txt","emp.txt");
}
void
main()
{
int
c=0;
clrscr();
while(c<5)
{
printf("\n\n\t1.
Add");
printf("\n\t2.
Display");
printf("\n\t3.
Delete");
printf("\n\t4.
Modify");
printf("\n\t5.
Exit");
printf("\n\tYour
Choice : ");
scanf("%d",&c);
switch(c)
{
case
1:add();break;
case
2:disp();break;
case
3:del ();break;
case
4:modify();break;
}
}
getch();
}
No comments:
Post a Comment