I have written this program in C. Data Accepting and showing part is working fine. But when i am trying to search a record and modify it with new data, it is not working.
#include <stdio.h>
#include <string.h>
int main()
{
int tf=0;
int i=0;
int j=0;
char temp[20];
FILE *fw,*fr;
char opsn='y';
char *p;
int count=0;
struct student
{
char name[20];
int age;
}s,s2;
int recsize=sizeof(s);
int taka;
char stnm[20];
char me[20];
int ge;
printf(" \n 1 add ");
printf(" \n 2 show ");
printf(" \n 3 modify");
scanf("%d",&taka);
if(taka==1)
{
fw=fopen("op.txt","a");
while(opsn=='y')
{
count++;
printf("Enter student name and age\n");
scanf("%s%d",&s.name,&s.age);
fprintf(fw,"%s\t%d\n",s.name,s.age);
printf("Want another record(y|n)\n");
fflush(stdin);
opsn=getche();
}
fclose(fw);
}
if(taka==2)
{
fr=fopen("op.txt","r");
printf("\nRecord from file is\n");
i=0;
while(fscanf(fr,"%s\t%d\n",s.name,&s.age)!=EOF)
{
printf("%s %d\n",s.name,s.age);
}
}
if(taka==3)
{
fr=fopen("op.txt","r+");
printf("\nEnter name of student to modify");
scanf("%s",&stnm);
printf("ok");
rewind(fr);
while(fscanf(fr,"%s\t%d\n",&s.name,&s.age)!=EOF)
{
if(strcmp(s.name,stnm)==0)
{
printf("\nenter new name,age");
scanf("%s%d",&me,&ge);
strcpy(s.name,me);
s.age=ge;
fseek(fr,recsize,SEEK_SET);
fprintf(fr,"%s\t%d\n",s.name,s.age);
break;
}
recsize = recsize * tf;
printf("%s %d %d\n",s.name,s.age,tf);
tf++;
}
printf(" Done ");
}
}
What I have tried:
tried with fread() and fwrite()
it is working.
But i want to do do same file updation program using
fprintf()
fscanf()