Files - 9 Search operation in file

Search operation in file

/* Program to search a particular student details in a file on the 
basis of roll number */

#include < stdio.h >
struct student
{
int rno;
char name[30];
};

main()
{
 FILE *fp;
 int vrno,found=0;
 struct student s;

 fp = fopen ( "Yourname.txt","r" );
 printf( "\n Enter the roll number to be searched : " );
 scanf( "%d", &vrno );
 while( ! feof (fp) )
  {
 fscanf( fp, "%d%s" ,&s.rno, s.name );
 if( vrno== s.rno )
   {
   printf(" \n Student found, details are as follows " );
   printf(" \n%5d%20s", s.rno, s.name );
   found=1;
   break;
   }
 }
 if( found==0 )
   printf( "\n Student with this roll number not found " );
}

Description:

In the previous two posts( 1. http://sridhanvantari.blogspot.com/2013/12/files-7-demonstrating-fprintf-function.html , 2. http://sridhanvantari.blogspot.com/2013/12/files-8-demonstrating-fscanf-function.html ) we have seen how to store and read the details of student from file. In this we will see how to apply search operation on the files. Assuming that yourname.txt file is created, initially the structure the student with member rno and name  are declared.  The required variables 

- pointer to file *fp
- vrno for holding the roll number to serached into the file.
- found is a status variable to indicate the successful / unsuccessful serach operation. It is initialised with value zero.
- structure variable of type student s is declared (To know more about structures, http://sridhanvantari.blogspot.com/2013/10/structures.html)

Using fopen() function a file "yourname.txt" is opened in read mode. (To read more about fopen and modes of file read, http://sridhanvantari.blogspot.com/2013/12/files-1-file-handling.html ) The roll number to searched into the file will be accepted and it will stored into the variable vrno. A while loop begins the execution until EOF (End of file) occurs. Inside the body of loop using fscanf() function (To read more about fscanf(),
http://sridhanvantari.blogspot.com/2013/12/files-8-demonstrating-fscanf-function.html ) the first student's roll number and name will read and it will stored into the structure members rno and name. Then the roll number read from file present in s.rno will be compared with search key vrno. If both gets matched a message "student found, details are as follows" will be printed on output screen. The search status variable found will be set to 1 and the loop will stop iterations and exits because of break statement. If both does not matched then loop continues with next iteration until EOF is reached. After the loop execution, the value of found variable will checked if it is 0 then it prints a message "
Student with this roll number not found ". If roll number present in vrno does not gets matched with any of the roll number then the found variable's initial value remain unchanged i.e. it will be zero. 

Comments