“Create a binary file with name and roll number. Search for a given roll number and display the name, if not found display an appropriate message” is a standard Class 12 computer science practical on binary files. It uses the pickle module in Python to save records in a file and then reads them back one by one to find a match. In this post you will see the complete program in Python, C and Java, a record-by-record dry run, nine other ways to write it, and answers to common questions. Use the interactive tool below to save your own students and search for any roll number.
Save students in a binary file, then search for a roll number and watch the file being read record by record.
Graphical view
Code
Output
What You Will Learn
- The problem statement
- What is a binary file and what is pickle?
- The program in Python, C and Java
- Dry run: found and not found
- Other ways: functions, dictionary, list, show all, append and more
- Common mistakes, practice questions and FAQ
Problem Statement
Create a binary file with name and roll number. Search for a given roll number and display the name, if not found display an appropriate message.
The program has two parts. First it asks for the number of students and the roll number and name of each one, and saves every student as one record in a binary file. Then it asks for a roll number, searches the file, and prints the name of that student, or the message Roll number not found. The interactive tool above accepts 1 to 6 students. Names are one word of letters, and roll numbers are whole numbers from 1 to 9999.
What Is a Binary File and What Is pickle?
A text file stores readable characters and is divided into lines. A binary file stores data as raw bytes, exactly as it is held in the computer’s memory. If you open a binary file in Notepad, you see unreadable symbols. Binary files are faster to read and write, and they can store lists, dictionaries and other objects as they are.
| Text file | Binary file | |
|---|---|---|
| Open modes | “r”, “w”, “a” | “rb”, “wb”, “ab” |
| Content | Readable characters in lines | Bytes, not readable in Notepad |
| Python tools | read(), write(), readline() | pickle.dump(), pickle.load() |
| Typical file name | story.txt | student.dat |
The Python module pickle turns an object into bytes and back. This process is called pickling and unpickling:
pickle.dump(obj, f)writes the objectobjinto the binary filef. Each call saves one record after the previous one.pickle.load(f)reads the next record from the file. When no record is left, it raisesEOFError(end of file).
Our record is a list with two items: [roll, name]. So rec[0] is the roll number and rec[1] is the name. A file can have many records, and they are always read back in the order in which they were saved.
C has no pickle. It writes the memory of a struct directly with fwrite() and reads it with fread(). Java uses DataOutputStream and DataInputStream, which write numbers with writeInt() and text with writeUTF().
The Program
Logic:
- Create: open
student.datin"wb"mode, read n, and for each student read the roll number and the name and save[roll, name]withpickle.dump(). Close the file. - Search: open the file in
"rb"mode and read the roll number to search. Setfound = False. - Load the records one by one. If
rec[0] == find, print the name, setfound = Trueand stop withbreak. - When the records end,
EOFErroris raised, and theexceptblock ends the loop quietly. - Close the file. If
foundis stillFalse, print “Roll number not found”.
Python program
import pickle
f = open("student.dat", "wb")
n = int(input("Enter number of students: "))
for i in range(n):
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
pickle.dump([roll, name], f)
f.close()
f = open("student.dat", "rb")
find = int(input("Enter roll number to search: "))
found = False
try:
while True:
rec = pickle.load(f)
if rec[0] == find:
print("Name:", rec[1])
found = True
break
except EOFError:
pass
f.close()
if found == False:
print("Roll number not found")
Output when the roll number is found
Enter number of students: 3
Enter roll number: 101
Enter name: Aman
Enter roll number: 102
Enter name: Riya
Enter roll number: 103
Enter name: Karan
Enter roll number to search: 102
Name: RiyaOutput when the roll number is not found
Enter number of students: 3
Enter roll number: 101
Enter name: Aman
Enter roll number: 102
Enter name: Riya
Enter roll number: 103
Enter name: Karan
Enter roll number to search: 999
Roll number not found
C program
#include <stdio.h>
struct Student {
int roll;
char name[30];
};
int main() {
FILE *f = fopen("student.dat", "wb");
int n;
struct Student s;
printf("Enter number of students: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter name: ");
scanf("%29s", s.name);
fwrite(&s, sizeof(s), 1, f);
}
fclose(f);
f = fopen("student.dat", "rb");
int find;
printf("Enter roll number to search: ");
scanf("%d", &find);
int found = 0;
while (fread(&s, sizeof(s), 1, f) == 1) {
if (s.roll == find) {
printf("Name: %s\n", s.name);
found = 1;
break;
}
}
fclose(f);
if (found == 0) {
printf("Roll number not found\n");
}
return 0;
}
For the same input, the C program prints Name: Riya. The structure struct Student is the record: an int and a char array for the name. fwrite(&s, sizeof(s), 1, f) writes one whole record, and fread(&s, sizeof(s), 1, f) reads one record and returns 1 if it succeeded, and 0 at the end of the file, which is how the loop knows when to stop. The names are read with %29s, so each name is one word of up to 29 letters.
Java program
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class BinarySearchRoll {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
DataOutputStream fout = new DataOutputStream(new FileOutputStream("student.dat"));
System.out.print("Enter number of students: ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("Enter roll number: ");
int roll = sc.nextInt();
System.out.print("Enter name: ");
String name = sc.next();
fout.writeInt(roll);
fout.writeUTF(name);
}
fout.close();
DataInputStream fin = new DataInputStream(new FileInputStream("student.dat"));
System.out.print("Enter roll number to search: ");
int find = sc.nextInt();
boolean found = false;
try {
while (true) {
int roll = fin.readInt();
String name = fin.readUTF();
if (roll == find) {
System.out.println("Name: " + name);
found = true;
break;
}
}
} catch (EOFException e) {
// end of file reached
}
fin.close();
if (!found) {
System.out.println("Roll number not found");
}
}
}
Save this file as BinarySearchRoll.java. For the same input, it prints Name: Riya. The reading order must match the writing order: an int first and then a UTF string. When the file ends, readInt() throws EOFException, which the catch block handles in the same way as Python’s EOFError.
Dry Run
The file holds three records: [101, "Aman"], [102, "Riya"] and [103, "Karan"]. First we search for 103.
| Step | Statement | rec | rec[0] == 103 | Result |
|---|---|---|---|---|
| 1 | rec = pickle.load(f) | [101, “Aman”] | False | try the next record |
| 2 | rec = pickle.load(f) | [102, “Riya”] | False | try the next record |
| 3 | rec = pickle.load(f) | [103, “Karan”] | True | print Name: Karan, found = True, break |
Now search for 999:
| Step | Statement | rec | rec[0] == 999 | Result |
|---|---|---|---|---|
| 1 | rec = pickle.load(f) | [101, “Aman”] | False | try the next record |
| 2 | rec = pickle.load(f) | [102, “Riya”] | False | try the next record |
| 3 | rec = pickle.load(f) | [103, “Karan”] | False | try the next record |
| 4 | rec = pickle.load(f) | no record left | EOFError, the loop ends, found is still False |
After the loop, if found == False is true, so the program prints Roll number not found. The search is a linear search: in the worst case it looks at every record, and the file has to be read from the beginning every time, because a binary file of this kind has no index.
Other Ways to Write the Program
Method 2: Separate functions for create and search
Functions make the program easier to read. search() returns the name, or None if nothing matched, so no flag is needed. The with statement closes the file automatically.
import pickle
def create():
with open("student.dat", "wb") as f:
n = int(input("Enter number of students: "))
for i in range(n):
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
pickle.dump([roll, name], f)
def search(find):
with open("student.dat", "rb") as f:
try:
while True:
rec = pickle.load(f)
if rec[0] == find:
return rec[1]
except EOFError:
return None
create()
find = int(input("Enter roll number to search: "))
name = search(find)
if name is None:
print("Roll number not found")
else:
print("Name:", name)
Method 3: Store one dictionary in the file
Instead of many small records, you can pickle one dictionary with the roll number as the key. Searching then becomes a single lookup, but the whole dictionary is loaded into memory.
import pickle
students = {}
n = int(input("Enter number of students: "))
for i in range(n):
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
students[roll] = name
with open("student.dat", "wb") as f:
pickle.dump(students, f)
with open("student.dat", "rb") as f:
data = pickle.load(f)
find = int(input("Enter roll number to search: "))
if find in data:
print("Name:", data[find])
else:
print("Roll number not found")
Method 4: Store one list of records
Here the file holds a single object, the list of all records. The for ... else structure runs the else block only when the loop ended without break, which means not found.
import pickle
records = []
n = int(input("Enter number of students: "))
for i in range(n):
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
records.append([roll, name])
with open("student.dat", "wb") as f:
pickle.dump(records, f)
with open("student.dat", "rb") as f:
records = pickle.load(f)
find = int(input("Enter roll number to search: "))
for rec in records:
if rec[0] == find:
print("Name:", rec[1])
break
else:
print("Roll number not found")
Method 5: Display all the records of the file
The same loop with EOFError can show everything that is in the file. This is a good way to check that the file was created correctly. After saving our three students, the program prints:
import pickle
with open("student.dat", "rb") as f:
try:
while True:
rec = pickle.load(f)
print(rec[0], rec[1])
except EOFError:
pass
101 Aman
102 Riya
103 Karan
Method 6: Add a record without erasing the old ones
Mode "ab" (append binary) adds new records at the end of the file.
import pickle
with open("student.dat", "ab") as f:
pickle.dump([104, "Neha"], f)
After this program, Method 5 shows:
101 Aman
102 Riya
103 Karan
104 Neha
Method 7: Handle a missing file
import pickle
try:
f = open("missing.dat", "rb")
rec = pickle.load(f)
f.close()
except FileNotFoundError:
print("File not found. Create the file first.")
File not found. Create the file first.
C: display all the records of the file
#include <stdio.h>
struct Student {
int roll;
char name[30];
};
int main() {
struct Student s;
FILE *f = fopen("student.dat", "rb");
if (f == NULL) {
printf("File not found\n");
return 1;
}
while (fread(&s, sizeof(s), 1, f) == 1) {
printf("%d %s\n", s.roll, s.name);
}
fclose(f);
return 0;
}
For our three students it prints:
101 Aman
102 Riya
103 Karan
The program checks that fopen() did not return NULL, so a missing file gives a message instead of a crash.
Common Mistakes
- Opening the file in text mode.
pickle.dump()writes bytes, so the file must be opened with"wb". With"w"Python stops with this error:
TypeError: write() argument must be str, not bytes
- Comparing a number with a string.
input()returns text. If you forgetint(),rec[0] == findcompares 102 with “102”, which is never equal, so every search says not found, even when the student exists:
Roll number not found
- Not handling EOFError. Without
try ... except EOFError, the program crashes when the records end:
import pickle
f = open("student.dat", "rb")
while True:
rec = pickle.load(f)
print(rec[0], rec[1])
EOFError: Ran out of input
- Using “wb” to add a record. Mode
"wb"erases the file every time it is opened. To keep the old records use"ab". - Forgetting to close the file after writing. The last records may stay in memory and be missing when you read the file. Close the file, or use
with open(). - Mixing the reading order in Java or the size in C. Data must be read in exactly the order and type in which it was written. In C, always use the same
structfor writing and reading. - Printing the message inside the loop. If “not found” is printed in an
elseof theifinside the loop, it is printed once for every record that does not match. Use a flag, or thefor ... elsestructure.
Practice Questions
- Add the marks of each student to the record, and display the name and marks of the searched roll number.
- Display all the students whose names start with the letter “A”.
- Update the name of a given roll number in the binary file.
- Delete the record of a given roll number. Hint: copy all the other records into a temporary file, then replace the old file.
- Count the number of records in the file.
- Search by name instead of the roll number.
- Stop the user from saving the same roll number twice.
Frequently Asked Questions
What is a binary file in Python?
A binary file stores data as bytes, not as readable text lines. You open it with the modes "rb", "wb" or "ab" and use the pickle module to write and read Python objects such as lists and dictionaries.
How do you create a binary file with a name and a roll number?
Open the file with open("student.dat", "wb"), read the roll number and the name, and save them with pickle.dump([roll, name], f). Repeat for every student and close the file.
How do you search a roll number in a binary file?
Open the file in "rb" mode and load the records one by one with pickle.load(f). Compare rec[0] with the roll number you want. Print rec[1], the name, when they match.
What is EOFError and why do we catch it?
EOFError means “end of file”. pickle.load() raises it when there is no record left to read. Python has no function that tells you in advance that the file has ended, so we read until the error occurs and catch it with except EOFError.
What is the difference between text files and binary files?
A text file stores readable characters in lines and uses modes such as "r" and "w". A binary file stores bytes and uses "rb" and "wb". Text files can be opened in Notepad, binary files cannot be read there.
What does pickle.dump() do?
It converts a Python object into bytes (pickling) and writes it to a binary file. pickle.load() reverses the process (unpickling) and gives you back the object.
What is the difference between “wb” and “ab”?
"wb" creates the file or erases an existing one before writing. "ab" keeps the old records and adds new ones at the end.
Why does my search always say “Roll number not found”?
The most common reasons are that the roll number was typed as text and not converted with int(), that the file was created again with "wb" and the old records were erased, or that the searched number is not stored in the file.
How do I do this in C and Java?
In C, define a struct with the roll number and the name, write it with fwrite() and read it back with fread(). In Java, use DataOutputStream.writeInt() and writeUTF() to save and DataInputStream.readInt() and readUTF() to read, and catch EOFException.
What is the time complexity of the search?
The program reads the records from the start until it finds a match, so it is a linear search with time complexity O(n) for n records. To search faster, store the data in a dictionary or a database.