Q: C Program to Search a Record by Name in Binary File
Input for C Program to Search Record by Name
This C program will take the name of student to search in the binary file.
How To Search a Record By Name in File?
This program will open the given file in read mode. We will use fread() standard library function to read a record at one time. The given name of student will be matched with the name in current student record. If the record is matched, the record of the student will be displayed on screen. The loop is terminated because of break statement.
How Names are Compared?
strcmp() standard library function compares the two strings. strcmp() function compares the two strings character by character.
- This standard function will check if all characters of strings are equal then String compare function will return 0 (zero) value.
- If the ASCII code of the first unmatched character is less than the corresponding character in second string, then strcmp() function will return a negative value.
- strcmp() funaction will return a positive value, if the ASCII code of first unmatched character is more than the corresponding character of second string.
while loop is used to read all records of c file one by one.
If no record matches with given name, a message “Record not found” will be displayed.
Note that we have already stored some records of students using a c program to write / save records in a binary file.
We will modify the c program to read and display records from a binary file.
The source code for this C program to perform a search by name in a binary file is as follows:
/* Write a C program to input a name then search the record of this student in a binary file */ #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<string.h> struct student { int rollno; char name[30]; }srecord; int main() { FILE *fptr; int found=0; char sname[30]; /*open binary file in read mode*/ fptr=fopen("d://sfile.dat","rb"); if(fptr==NULL) { printf("File could not open"); exit(0); } printf("\n Enter Name of Student to Search Record="); gets(sname); while((fread(&srecord,sizeof(srecord),1,fptr)==1)) { if(srcmp(srecord.name,sname)==0) { found=1; printf("\nRecord of Student With Name %s is as follows:",sname); printf("\n======================="); printf("\nRoll No:%d",srecord.rollno); printf("\nName:%s",srecord.name); printf("\n======================="); break; } } if(found==0) printf("\n Record Not found in this file!"); fclose(fptr); return 0; }
Note: This C program will show only the first matching record with given name of student in the binary file. If you wish to write a C program to search all records related to given name, click here.
Pingback: C Program to Search Multiple Records of Given Name in Binary File » EasyCodeBook.com