Create a binary file with roll number, name and marks. Input a roll number and update the marks program in Python, C and Java

“Create a binary file with roll number, name and marks. Input a roll number and update the marks” is a very common Class 12 computer science practical. You save student records in a binary file with pickle, search for a roll number, change the marks and write the change back into the file. The tricky part is that a binary file cannot be edited like a text document. In this post you will get the complete program in Python, C and Java, a record-by-record dry run, two ways to update (in place with seek() and by rewriting the file), common mistakes with real error messages, and an FAQ. Use the interactive tool below to try your own students.

★ Binary File: Update the Marks of a Roll Number

Save students in a binary file, then enter a roll number and new marks and watch the record being updated.

Graphical view

Code

Output

What You Will Learn

Problem Statement

Create a binary file with roll number, name and marks. Input a roll number and update the marks.

The program saves the roll number, name and marks of each student as one record. Then it asks for a roll number and the new marks, finds the record, changes the marks, and prints Marks updated. If the roll number does not exist, it prints Roll number not found and leaves the file as it was. At the end it reads the file again and prints all the records, so you can see the change. The interactive tool above accepts 1 to 5 students, roll numbers from 1 to 9999, one-word names and marks from 0 to 100.

How a Binary File Is Updated

A text file can be opened and changed in a text editor. A binary file is a sequence of records stored one after another, and the program has to find the record and replace it. There are two standard methods, and both are used in board practicals.

Method 1: in placeMethod 2: rewrite
File mode“rb+” (read and write)“rb” to read, then “wb” to write
Main ideaRemember the position, seek back, overwrite one recordLoad all the records, change one, write all again
Needstell() and seek()A list to hold the records
Memory usedOne recordAll records
Safe to use ifThe new record has the same size as the old oneAlways

Method 1 depends on the file pointer. The pointer is the position from where the next read or write will happen. When pickle.load(f) reads a record, the pointer moves to the start of the next record. If you wrote the new record right now, it would be saved over the next student. So the program calls pos = f.tell() before loading a record, and calls f.seek(pos) after the match to move the pointer back to the start of the correct record. Then pickle.dump(rec, f) overwrites that one record.

The new record must have the same size as the old record. Marks are whole numbers from 0 to 100, which pickle stores in the same number of bytes, so the size does not change and the next record stays safe. This is also why the Java version stores the name in a fixed 10 bytes, and why the C version uses a struct of fixed size.

The Program

Logic (Method 1, in place):

  • Create: open student.dat in "wb" mode and save [roll, name, marks] for each student with pickle.dump(). Close the file.
  • Update: open the file in "rb+" mode. Read the roll number to update (find) and the new marks (newm). Set found = False.
  • In a loop, remember pos = f.tell() and then load a record.
  • If rec[0] == find, set rec[2] = newm, move back with f.seek(pos), write the record with pickle.dump(rec, f), set found = True and break.
  • If the records end first, EOFError ends the loop. Close the file and print the message.
  • Finally, open the file in "rb" mode and print every record to show the result.

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: ")
    marks = int(input("Enter marks: "))
    pickle.dump([roll, name, marks], f)
f.close()
f = open("student.dat", "rb+")
find = int(input("Enter roll number to update: "))
newm = int(input("Enter new marks: "))
found = False
try:
    while True:
        pos = f.tell()
        rec = pickle.load(f)
        if rec[0] == find:
            rec[2] = newm
            f.seek(pos)
            pickle.dump(rec, f)
            found = True
            break
except EOFError:
    pass
f.close()
if found == True:
    print("Marks updated")
else:
    print("Roll number not found")
f = open("student.dat", "rb")
print("Records in the file:")
try:
    while True:
        rec = pickle.load(f)
        print(rec[0], rec[1], rec[2])
except EOFError:
    pass
f.close()

Output when the roll number is found

Enter number of students: 3
Enter roll number: 101
Enter name: Aman
Enter marks: 82
Enter roll number: 102
Enter name: Riya
Enter marks: 68
Enter roll number: 103
Enter name: Karan
Enter marks: 91
Enter roll number to update: 102
Enter new marks: 90
Marks updated
Records in the file:
101 Aman 82
102 Riya 90
103 Karan 91

Output when the roll number is not found

Enter number of students: 3
Enter roll number: 101
Enter name: Aman
Enter marks: 82
Enter roll number: 102
Enter name: Riya
Enter marks: 68
Enter roll number: 103
Enter name: Karan
Enter marks: 91
Enter roll number to update: 999
Enter new marks: 50
Roll number not found
Records in the file:
101 Aman 82
102 Riya 68
103 Karan 91
C program
#include <stdio.h>
struct Student {
    int roll;
    char name[30];
    int marks;
};
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);
        printf("Enter marks: ");
        scanf("%d", &s.marks);
        fwrite(&s, sizeof(s), 1, f);
    }
    fclose(f);
    f = fopen("student.dat", "rb+");
    int find, newm;
    printf("Enter roll number to update: ");
    scanf("%d", &find);
    printf("Enter new marks: ");
    scanf("%d", &newm);
    int found = 0;
    while (fread(&s, sizeof(s), 1, f) == 1) {
        if (s.roll == find) {
            s.marks = newm;
            fseek(f, -(long)sizeof(s), SEEK_CUR);
            fwrite(&s, sizeof(s), 1, f);
            found = 1;
            break;
        }
    }
    fclose(f);
    if (found == 1) {
        printf("Marks updated\n");
    } else {
        printf("Roll number not found\n");
    }
    f = fopen("student.dat", "rb");
    printf("Records in the file:\n");
    while (fread(&s, sizeof(s), 1, f) == 1) {
        printf("%d %s %d\n", s.roll, s.name, s.marks);
    }
    fclose(f);
    return 0;
}

C reads and writes one struct Student at a time. After fread() the pointer is at the next record, so fseek(f, -(long)sizeof(s), SEEK_CUR) moves it back by exactly one record. Then fwrite() replaces the record. A binary file in C must be opened with "rb+" so that it can be read and written. When switching between reading and writing on the same file, C requires a call such as fseek() in between, and the program already has one.

Java program
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
public class UpdateMarks {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        RandomAccessFile f = new RandomAccessFile("student.dat", "rw");
        f.setLength(0);
        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();
            System.out.print("Enter marks: ");
            int marks = sc.nextInt();
            f.writeInt(roll);
            f.writeBytes(String.format("%-10s", name));
            f.writeInt(marks);
        }
        f.close();
        f = new RandomAccessFile("student.dat", "rw");
        System.out.print("Enter roll number to update: ");
        int find = sc.nextInt();
        System.out.print("Enter new marks: ");
        int newm = sc.nextInt();
        boolean found = false;
        long len = f.length();
        while (f.getFilePointer() < len) {
            long pos = f.getFilePointer();
            int roll = f.readInt();
            byte[] nb = new byte[10];
            f.readFully(nb);
            int marks = f.readInt();
            if (roll == find) {
                // marks field starts 14 bytes after the record start
                f.seek(pos + 14);
                f.writeInt(newm);
                found = true;
                break;
            }
        }
        f.close();
        if (found) {
            System.out.println("Marks updated");
        } else {
            System.out.println("Roll number not found");
        }
        f = new RandomAccessFile("student.dat", "r");
        System.out.println("Records in the file:");
        while (f.getFilePointer() < f.length()) {
            int r = f.readInt();
            byte[] nb2 = new byte[10];
            f.readFully(nb2);
            int m = f.readInt();
            System.out.println(r + " " + new String(nb2).trim() + " " + m);
        }
        f.close();
    }
}

Save this file as UpdateMarks.java. RandomAccessFile in "rw" mode lets Java read and write at any position. Each record is 4 bytes for the roll number, 10 bytes for the name and 4 bytes for the marks, so the marks start 14 bytes after the start of the record. The program does f.seek(pos + 14) and writes only the new marks with writeInt().

Dry Run

The file holds [101, "Aman", 82], [102, "Riya", 68] and [103, "Karan", 91]. We update roll number 102 to 90.

StepStatementposrecrec[0] == 102Action
1load record 1start of record 1[101, “Aman”, 82]Falsego to the next record
2load record 2start of record 2[102, “Riya”, 68]Truerec[2] = 90, seek(pos), dump, found = True, break

Record 3 is never read. The file before and after the update:

RecordBeforeAfter
1101 Aman 82101 Aman 82
2102 Riya 68102 Riya 90
3103 Karan 91103 Karan 91

For the not-found search (roll number 999), all three records are read, then EOFError occurs, found stays False, and the file is not written at all.

Other Ways to Update

Method 2: Load all records and rewrite the file

This is the safest method. It reads every record into a list, changes the matching one, and writes the whole list back with "wb", which first erases the file. The tool above shows this method when you choose Rewrite the whole file.

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: ")
    marks = int(input("Enter marks: "))
    pickle.dump([roll, name, marks], f)
f.close()
f = open("student.dat", "rb")
find = int(input("Enter roll number to update: "))
newm = int(input("Enter new marks: "))
found = False
records = []
try:
    while True:
        rec = pickle.load(f)
        if rec[0] == find:
            rec[2] = newm
            found = True
        records.append(rec)
except EOFError:
    pass
f.close()
if found == True:
    f = open("student.dat", "wb")
    for rec in records:
        pickle.dump(rec, f)
    f.close()
    print("Marks updated")
else:
    print("Roll number not found")
f = open("student.dat", "rb")
print("Records in the file:")
try:
    while True:
        rec = pickle.load(f)
        print(rec[0], rec[1], rec[2])
except EOFError:
    pass
f.close()
C and Java versions of the rewrite method
#include <stdio.h>
struct Student {
    int roll;
    char name[30];
    int marks;
};
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);
        printf("Enter marks: ");
        scanf("%d", &s.marks);
        fwrite(&s, sizeof(s), 1, f);
    }
    fclose(f);
    f = fopen("student.dat", "rb");
    int find, newm;
    printf("Enter roll number to update: ");
    scanf("%d", &find);
    printf("Enter new marks: ");
    scanf("%d", &newm);
    int found = 0;
    struct Student list[50];
    int count = 0;
    while (fread(&s, sizeof(s), 1, f) == 1) {
        if (s.roll == find) {
            s.marks = newm;
            found = 1;
        }
        list[count] = s;
        count++;
    }
    fclose(f);
    if (found == 1) {
        f = fopen("student.dat", "wb");
        fwrite(list, sizeof(struct Student), count, f);
        fclose(f);
        printf("Marks updated\n");
    } else {
        printf("Roll number not found\n");
    }
    f = fopen("student.dat", "rb");
    printf("Records in the file:\n");
    while (fread(&s, sizeof(s), 1, f) == 1) {
        printf("%d %s %d\n", s.roll, s.name, s.marks);
    }
    fclose(f);
    return 0;
}
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Scanner;
public class UpdateMarks {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        RandomAccessFile f = new RandomAccessFile("student.dat", "rw");
        f.setLength(0);
        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();
            System.out.print("Enter marks: ");
            int marks = sc.nextInt();
            f.writeInt(roll);
            f.writeBytes(String.format("%-10s", name));
            f.writeInt(marks);
        }
        f.close();
        f = new RandomAccessFile("student.dat", "rw");
        System.out.print("Enter roll number to update: ");
        int find = sc.nextInt();
        System.out.print("Enter new marks: ");
        int newm = sc.nextInt();
        boolean found = false;
        ArrayList<Integer> rolls = new ArrayList<>();
        ArrayList<String> names = new ArrayList<>();
        ArrayList<Integer> marksList = new ArrayList<>();
        long len = f.length();
        while (f.getFilePointer() < len) {
            int roll = f.readInt();
            byte[] nb = new byte[10];
            f.readFully(nb);
            int marks = f.readInt();
            if (roll == find) {
                marks = newm;
                found = true;
            }
            rolls.add(roll);
            names.add(new String(nb));
            marksList.add(marks);
        }
        f.close();
        if (found) {
            f = new RandomAccessFile("student.dat", "rw");
            f.setLength(0);
            for (int i = 0; i < rolls.size(); i++) {
                f.writeInt(rolls.get(i));
                f.writeBytes(names.get(i));
                f.writeInt(marksList.get(i));
            }
            f.close();
            System.out.println("Marks updated");
        } else {
            System.out.println("Roll number not found");
        }
        f = new RandomAccessFile("student.dat", "r");
        System.out.println("Records in the file:");
        while (f.getFilePointer() < f.length()) {
            int r = f.readInt();
            byte[] nb2 = new byte[10];
            f.readFully(nb2);
            int m = f.readInt();
            System.out.println(r + " " + new String(nb2).trim() + " " + m);
        }
        f.close();
    }
}

Both versions keep the records in memory (an array in C, lists in Java), change the marks and write everything again from the beginning of the file. For the same input they print the same result as the in-place version.

Method 3: Write to a temporary file

Many textbooks copy the records to a second file, then delete the old file and rename the new one. The original file is never half-written, and only one record is in memory at a time. This program assumes that student.dat already exists. We change roll number 102 to 77:

import pickle, os
find = int(input("Enter roll number to update: "))
newm = int(input("Enter new marks: "))
found = False
fin = open("student.dat", "rb")
fout = open("temp.dat", "wb")
try:
    while True:
        rec = pickle.load(fin)
        if rec[0] == find:
            rec[2] = newm
            found = True
        pickle.dump(rec, fout)
except EOFError:
    pass
fin.close()
fout.close()
os.remove("student.dat")
os.rename("temp.dat", "student.dat")
if found == True:
    print("Marks updated")
else:
    print("Roll number not found")
Enter roll number to update: Enter new marks: Marks updated
101 Aman 82
102 Riya 77
103 Karan 91

Method 4: Use a function

A function makes the update reusable. It returns True if the record was found. Here it changes roll number 103 to 99 in the file created in the first example:

import pickle
 
def update(find, newm):
    with open("student.dat", "rb") as f:
        records = []
        try:
            while True:
                records.append(pickle.load(f))
        except EOFError:
            pass
    found = False
    for rec in records:
        if rec[0] == find:
            rec[2] = newm
            found = True
    if found:
        with open("student.dat", "wb") as f:
            for rec in records:
                pickle.dump(rec, f)
    return found
 
if update(103, 99):
    print("Marks updated")
else:
    print("Roll number not found")
Marks updated
101 Aman 82
102 Riya 90
103 Karan 99

Show all records

This helper program prints the file. It is the last part of the main program and is also useful to check your file at any time. Before the update, the file shows:

import pickle
with open("student.dat", "rb") as f:
    try:
        while True:
            rec = pickle.load(f)
            print(rec[0], rec[1], rec[2])
    except EOFError:
        pass
101 Aman 82
102 Riya 68
103 Karan 91

After updating roll number 102 to 90:

101 Aman 82
102 Riya 90
103 Karan 91

Common Mistakes

  • Opening the file with “wb” to update. Mode "wb" erases the file as soon as it is opened, so there is nothing left to read, and the program stops with:
io.UnsupportedOperation: read
  • Opening with “rb” and then writing. A file opened for reading only cannot be written. Use "rb+":
io.UnsupportedOperation: write
  • Forgetting f.seek(pos). After pickle.load() the pointer is at the next record, so the new record is written in the wrong place and damages the following record. Without the seek line, updating roll number 101 gives:
101 Aman 82
101 Aman 55
103 Karan 91
  • Calling tell() after the load. It must be called before pickle.load(), because it should return the start of the record you are about to read.
  • Comparing text with a number. If you forget int() for the roll number, rec[0] == find is never true and every search prints “Roll number not found”.
  • Printing “not found” inside the loop. Use a found flag and check it after the loop.
  • Not closing the file. Close the file after the update, otherwise the change may not be saved when you read the file again.

Practice Questions

  1. Update the marks of every student whose roll number is in a given range.
  2. Add 5 grace marks to every student who has less than 33, and show the new file.
  3. Update the name of a given roll number.
  4. Delete the record of a given roll number using a temporary file.
  5. Insert a new record only if the roll number is not already in the file.
  6. Display the student with the highest marks.
  7. Show the count of students who passed (marks 33 or more).

Frequently Asked Questions

How do you update a record in a binary file in Python?

Open the file in "rb+" mode, remember the position with f.tell(), load the record with pickle.load(), and if it matches, change the value, call f.seek(pos) and write the record again with pickle.dump(). As another method, load all the records into a list, change one and rewrite the file with "wb".

What does the rb+ mode mean?

rb+ opens an existing binary file for both reading and writing, without erasing it. The pointer starts at the beginning of the file.

What do tell() and seek() do?

f.tell() returns the current position of the file pointer. f.seek(pos) moves the pointer to the position pos. Together they let you go back to the start of a record you have just read.

Why do we call seek() before dump()?

After pickle.load() the file pointer is at the beginning of the next record. Without seek() the updated record would overwrite the next student instead of the matching one.

What is the difference between “wb”, “rb” and “rb+”?

"wb" creates or erases the file and allows writing only. "rb" allows reading only. "rb+" allows reading and writing and keeps the old content.

Why does the new record need to be the same size?

In the in-place method the new record is written over the old one. If it were longer, it would overwrite part of the next record. Whole-number marks from 0 to 100 take the same space, so they are safe. If the size can change, use the rewrite method.

What happens if the roll number is not in the file?

The loop reads all the records and ends with EOFError. The flag found is still False, so the program prints “Roll number not found” and the file is not changed.

Which method is better, in place or rewrite?

The in-place method is faster and uses less memory, but it needs seek() and records of equal size. The rewrite method is easier to write and safe for any record size, but it loads everything in memory. In exams, either is accepted if the logic is correct.

How is it done in C and Java?

In C, open the file with "rb+", read a struct with fread(), go back with fseek(f, -sizeof(s), SEEK_CUR) and write it with fwrite(). In Java, use RandomAccessFile in "rw" mode, seek() to the marks field and writeInt().

Can I update a binary file in Notepad?

No. A binary file is not made of readable lines, and saving it from a text editor will damage it. Always update it with a program.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top