Binary Files & Random Access File Handling

0
186
Binary Files & Random Access File Handling

Binary Files & Random Access File Handling is a powerful combination in C and C++ that allows you to manipulate structured data efficiently. Whether you’re working on an employee database, a game save system, or a file archive, knowing how to store and retrieve information with precision is essential.

This tutorial, curated by Kamlesh Singad from Code With Kamlesh, is designed to teach you the theory and practice of handling binary files and using random access techniques, a vital continuation in the Strings & File Handling module of the C/C++ course.

Importance in Modern Programming

File handling isn’t just about reading or writing data—sometimes you need speed, structure, and direct control. That’s where:

  • Binary files give compact, structured storage
  • Random access allows you to jump directly to the needed part of a file

Used in systems like databases, games, and multimedia apps, these skills are indispensable.

Also Read: Inline Functions & Function Overloading in C++

Binary Files & Random Access File Handling

What Are Binary Files?

A binary file is a file that contains data in a format not intended to be human-readable. Examples include .exe, .bin, .dat, and even image files like .jpg.

They are:

  • More space-efficient
  • Faster to read and write
  • Ideal for storing structs and large data blocks

Binary vs Text Files

FeatureBinary FileText File
FormatNon-readableHuman-readable
SizeCompactUsually larger
SpeedFaster I/OSlower
Use CaseData structures, mediaLogs, configs

Binary File Handling in C

Writing to a Binary File

#include <stdio.h>

struct Student {
    int id;
    char name[50];
};

int main() {
    struct Student s1 = {1, "Amit"};
    FILE *fp = fopen("students.dat", "wb");
    fwrite(&s1, sizeof(s1), 1, fp);
    fclose(fp);
    return 0;
}

Reading from a Binary File

struct Student s2;
FILE *fp = fopen("students.dat", "rb");
fread(&s2, sizeof(s2), 1, fp);
printf("%d %s", s2.id, s2.name);
fclose(fp);

Introduction to Random Access File Handling

Random access allows you to:

  • Jump to any part of a file
  • Read/write without reading the whole file
  • Efficiently update, delete, or insert records

Also Read: Recursion in C/C++: Understanding Recursive Functions

Binary Files & Random Access File Handling

File Pointers and fseek() in C

fseek(fp, sizeof(struct Student) * 2, SEEK_SET);

This moves the file pointer to the 3rd student record.

Use:

  • SEEK_SET – Beginning of file
  • SEEK_CUR – Current position
  • SEEK_END – End of file
long pos = ftell(fp);  // Get current position
rewind(fp);            // Move pointer to beginning

Practical Example: Employee Record System

struct Employee {
    int id;
    char name[50];
    float salary;
};

// Modify salary for a given ID
void updateRecord(FILE *fp, int id) {
    struct Employee emp;
    while (fread(&emp, sizeof(emp), 1, fp)) {
        if (emp.id == id) {
            emp.salary += 1000;
            fseek(fp, -sizeof(emp), SEEK_CUR);
            fwrite(&emp, sizeof(emp), 1, fp);
            break;
        }
    }
}

Binary Files & Random Access in C++

Writing Binary in C++

#include <fstream>
using namespace std;

struct Student {
    int id;
    char name[50];
};

Student s = {101, "Raj"};
ofstream file("data.bin", ios::binary);
file.write((char*)&s, sizeof(s));
file.close();

Random Access Using seekg() and seekp()

ifstream file("data.bin", ios::binary);
file.seekg(2 * sizeof(Student), ios::beg);  // Go to 3rd record
Student s;
file.read((char*)&s, sizeof(s));
file.close();
Binary Files & Random Access File Handling

Best Practices

  • Always close() your files.
  • Validate file opening using if (!file) or if (fp == NULL)
  • Pack your structures (avoid padding)
  • Handle endianness when moving between systems

Also Read: Functions in C/C++: Declaration, Definition, and Calling

FAQs

What is the difference between text and binary files?
Text files are readable to humans; binary files store data in raw formats and are more efficient.

Why use random access file handling?
To quickly access or modify specific data without reading the entire file.

How do I use fseek in C?
fseek(filePtr, offset, origin) changes the file pointer’s position for reading/writing.

Can we use strings in binary file handling?
Yes, especially when storing arrays of characters or fixed-size string buffers in structs.

What’s the risk of binary files?
Less portable due to system-specific data alignment and endianness.

What real-world apps use random access?
Databases, media players, log viewers, and compilers.

Conclusion

Mastering Binary Files & Random Access File Handling in C/C++ empowers you to manage data with precision and speed. With guidance from Kamlesh Singad at Code With Kamlesh, you’ve explored both theoretical insights and real-life coding practices in this continuation of the Strings & File Handling segment.

LEAVE A REPLY

Please enter your comment!
Please enter your name here