Search This Blog

Thursday, 24 August 2017

Creation, insertion and deletion of records from a file using linked list in C

#include <stdio.h>
#include <stdlib.h>
struct emp
{
 int eno;
 char ename[25];
 int salary;
 struct emp *next;
};
struct emp*new1=NULL,*start=NULL,*temp=NULL;
void accept()
{
 new1=(struct emp *) malloc(sizeof(struct emp));
 printf("Employee Number..");
 scanf("%d",&new1->eno);
 printf("Employee Name...");
 scanf("%s",new1->ename);
 printf("Employee salaray...");
 scanf("%d",&new1->salary);
}
void ReadFile()
{
 FILE *fp;
 fp=fopen("emp.dat","r");
 if(fp==NULL)
 return;

 while(1)
 {
  new1=(struct emp *)malloc(sizeof(struct emp));
  fread(new1,sizeof(struct emp),1,fp);
  if(feof(fp))
  break;
  if((start==NULL)
  {
   start=new1;
   temp=new1;
   temp->next=NULL;
  }
  else
  {
   temp->next=new1;
   temp=new1;
   temp->next=NULL;
  }
 }
 fclose(fp);
}
void WriteFile()
{
 FILE *fp;
 fp=fopen("emp.dat","W");

 for(new1=start;new1!=NULL;new1=new1->next)
 {
  fwrite(new1,sizeof(struct emp),1,fp);
 }
 fclose(fp);
}
void main()
{
 struct emp *new2,*dPtr;
 char ch='y';
 int recno;
 clrscr();
 ReadFile();
 while(ch=='y')
 {
  accept();
  fflush(stdin);
  if(start==NULL)
  {
   start=new1;
   temp=new1;
   temp->next=NULL;
  }
  else
  {
   temp->next=new1;
   temp=new1;
   temp->next=NULL;
  }
  printf("Do u want to continue..");
  scanf("%c",&ch);
}
for(new1=start;new1!=NULL;new1=new1->next)
{
 printf("%d %s %d \n",new1->eno,new1->ename,new1->salary);
}
prinf("enter the recno to be inserted...");
scanf("%d",&recno);
accept();
for(new2=start;new2!=NULL;new2=new2->next)
{
 if(start->eno==recno)
 {
  new1->next=start;
  start=new1;
 }
else if(new2->eno==recno && new2->next != NULL)
{
 temp->next = new1;
 new1->next = new2;
}
else if(new2->eno==recno && new2->next== NULL)
{
 new2->next=new1;
 new1->next=NULL;
}
temp=new2;
}
for(new1=start;new1!=NULL;new1=new1->next)
{
 print("%d %s %d \n",new1->ename,new1->salary);
}
print("Enter the recno to delete...");
scanf("%d",&recno);
for(new1=start;new1=NULL;new1=new1->next)
{
 if(start->eno == recno)
 {
  dPtr=start;
  start=start->next;
  free(dptr);
 }
 else if(new1->eno==recno && new1->next != NULL)
 {
  dPtr=new1;
  temp->next=new1->next;
  free(dPtr);
 }
 else if(new1->eno==recno && new1->next == NULL)
 {
  dPtr=temp->next;
  temp->next=NULL;
  free(dPtr);
 }
 temp=new1;
}

printf("Enter the recno to modify...");
scanf("%d",&recno);
for(new1=start;new1!=NULL;new1=new1->next)
{
 if(new1->eno==recno)
 {
  printf("Enter the employee name..");
  scanf("%s",new1->ename);
 }
}
for(new1=start;new1!=NULL;new1=new1->next)
{
 printf("%d %s %d \n",new1->eno,new1->ename,new1->salary);
}
WriteFile();
new1=start;
while(1)
{
 temp=new1;
 new1=new1->next;
 free(temp);
 if(new1==NULL)
 break;
}
temp=NULL;
new1=NULL;
new2=NULL;
dPtr=NULL;
start=NULL;
getch();
}

No comments:

Post a Comment