Searching of Record from Data File

#include<stdio.h>
#include<conio.h>
struct item
{
          int no,qty;
          float price;
          char iname[10];
};
void main()
 {
          FILE *fp;
          long size;
          int c=1,x;
          struct item i;
          char ans;
          clrscr();
          fp=fopen("data.txt","wb+");
          printf("\n ========Enter Data=======");
          do
          {
                   printf("\n------- Record - %d --------",c);
                   fflush(stdin);
                   printf("\nEnter item number  : ");
                   scanf("%d",&i.no);
                   fflush(stdin);
                   printf("\nEnter item name    : ");
                   gets(i.iname);
                   fflush(stdin);
                   printf("\nEnter price        : ");
                   scanf("%f",&i.price);
                   printf("\nEnter Quantity     : ");
                   scanf("%d",&i.qty);
                   fwrite(&i,sizeof(i),1,fp);
                   fflush(stdin);
                   printf("\n Do you want to continue [y-n] : ");
                   ans=getchar();
                   if(ans=='y' || ans=='Y')
                    {
                             c++;
                    }
          }while(ans=='y' || ans=='Y');
          rewind(fp);
          printf("\n Enter record number for searching : ");
          scanf("%d",&x);
          if(x<=c)
            {
                   x--;
                   fseek(fp,x*sizeof(i),0);
                   printf("\nPosition Of the pointer in file: %ld\n",ftell(fp));
                   fread(&i,sizeof(i),1,fp);
                   printf("\n\n %d %s  %f  %d \n",i.no,i.iname,i.price,i.qty);
            }
          else
           {
              printf("\n No record found ");
           }
          getch();
}

Post a Comment

Previous Post Next Post