Thursday, May 17, 2012

Prog-12


#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#include<string.h>

#include<iostream.h>

#include<fstream.h>

#include<new.h>

class node

{

 public:char name[20];

        char usn[20];

        node *link;

};



node *first=NULL;



void writeFile()

{

  node *p;

  char buffer[100];

  fstream out;



  out.open("student.txt",ios::out);



  if(!out)

  {

   cout<<"\nUnable to open the file student.txt in out mode";

   getch();

   exit(0);

  }



  p=first;

  while(p!=NULL)

  {

    strcpy(buffer,p->name);

    strcat(buffer,"|");

    strcat(buffer,p->usn);

    strcat(buffer,"\n");

    out<<buffer;

    p=p->link;

  }



}





void display()

{

 node *p;



 if(first==NULL)

 {

  cout<<"\nList is empty";

  return;

 }



  p=first;



 while(p!=NULL)

 {

  cout<<"|"<<p->name<<" "<<p->usn<<"|"<<"->";

  p=p->link;

 }



}





void Insert() //Insert the record at the rear end

{



 char name[20],usn[15];

 node *p,*q;





 cout<<"\nEnter name  = ";

 cin>>name;

 cout<<"\nEnter usn   = ";

 cin>>usn;

  p=new node;

 strcpy(p->name,name);

 strcpy(p->usn,usn);

 p->link=NULL;



 if(first==NULL)

 {

   first=p;

   writeFile();

   display();    //display the record on the screen

   return;

 }



 for(q=first;q->link!=NULL;q=q->link)

 {

  ;

 }



 q->link=p;



 writeFile(); //writing the record to the file

 display();   //display the records to the screen.



}





void Delete()

{

  char usn[15];

  node *curr,*prev,*del;



 if(first==NULL)

 {

  printf("\nThe list is empty. Deletion is not possible");

  return;

 }



 cout<<"\nEnter the usn to be deleted = ";

 cin>>usn;



 if(strcmp(first->usn,usn)==0)

 {



  cout<<"\nRecord deleted";

  del=first;

  delete del;

  first=first->link;

  writeFile();

  return;



 }



 prev=NULL;

 curr=first;

 while( ( strcmp(curr->usn,usn) != 0 ) && curr!=NULL)

 {

   prev=curr;

   curr=curr->link;

 }



 if(curr==NULL)

 {

    cout<<"\nThe student with usn "<<usn<<" is not present";

    return;

 }



 prev->link=curr->link;



 writeFile();

 display();



}

void main()

{

 int choice;

 clrscr();

 for(;;)

 {

  printf("\n1:Insert_rear");

  printf("\n2:Delete_id");

  printf("\n3:exit");



  printf("\nEnter the choice=");

  scanf("%d",&choice);



  switch(choice)

  {

   case 1:Insert();

          break;

   case 2:Delete();

          break;

   case 3:exit(0);

  default:cout<<"\nInvalid option";break;

  }

 }

}

No comments:

Post a Comment