0

The program runs fine till I create the file and enter records from structure, but when I try to search a record by using roll no, it crashes.

I am using a structure called student to store data and then I am creating a text file and then I use a for loop to write data on the text file. Then I reopen the file and try to search a record using student roll no.

Program runs fine until I try to search the student roll no. It crashes right after I enter the student roll no to be searched.

Can anyone tell me what modification is needed to make the search work?

Below is my code:

#include<stdio.h>


 struct student {

    int roll_no;
    char name [80];
    int age;

    }st[30],s;



   int main ()

{
int i,n;
char fname[80];
int search;
int found;

FILE *fp;

printf("\nEnter the file name : \n");
scanf("%s",fname);
fp=fopen(fname,"w");
if(fp==NULL)
{
    printf("\nCannot create file :");
    exit(0);
}

printf("\nNumber of students : \n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
    printf("\n\nInformation for student#%d : \n\n",i+1);

    printf("\nStudent roll number :  \n" );
    scanf("%d",&st[i].roll_no);
    printf("\nStudent name: \n: ");
    scanf("%s",st[i].name);
    printf("\nStudent age : ");
    scanf("%d", &st[i].age);

}

fprintf(fp, "\nStudent roll no\t\t Student name\t\t student age\t\t\n\n");
for(i=0;i<n;i++)
{
    fprintf(fp, "\n%d          \t\t %s           \t\t %d          \t\t", st[i].roll_no,st[i].name,st[i].age);


}
fclose(fp);

fp=fopen(fname,"r+t");
if(fp==NULL)
{
    printf("\nCannot open file\n");
    exit(0);
}
printf("\n\nStudent roll no to be searched : ");
found=0;
scanf("%d", search);


while(!(feof(fp)) && (found==0))
{
    fscanf(fp,"%d,%s,%d",&s.roll_no,s.name,&s.age);
    if(s.roll_no==search)
    {
        fseek(fp,-sizeof(struct student), SEEK_CUR);
        printf("\nEnter new name : \n");
        scanf("%s", s.name);
        fprintf(fp, "\n%d          \t\t %s           \t\t %d          \t\t", s.roll_no,s.name,s.age);

        found=1;
    }
}

if(found=0)
{
    printf("\nStudent record doesn't exist \n");
}
fclose(fp);
return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

1 Answers1

2

In your code, you're missing an address-of operator in scanf(), thereby passing an invalid type of argument. Basically

 scanf("%d", search);

should be

scanf("%d", &search);

That said, it is always a good practice to size-limit the inputs for string, like, for an array defined like char fname[80];, you should use

scanf("%79s",fname);

to avoid possible buffer overflow by excessively long input.

Also, always check for the return value of scanf() and family of functions to ensure their success.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261