Reading Binary Files in C++

Reading Binary Files in C++

Reading the binary files requires some special methods in C++ to handle the raw data efficiently. There are various methods to read a normal text file, but you cannot use them to read a binary file. Here is a method that can be used to read a binary file, i.e., the  std::ifstream::read() method in C++.

Table of Contents:

What is std::ifstream::read() in C++?

The std::ifstream::read() in C++ is used to read the binary files or raw bytes from a file into a character buffer. It reads exact bytes and preserves the formatting in a file.

Syntax:

std::istream& read(char* s, std::streamsize n);

Parameters:

  • s: It is a pointer to a character array or buffer where the data will be stored.
  • n: The number of bytes to read.

Returns: It returns a reference to std::isteam.

How to Use ifstream::read to Read Binary Files in C++?

You can use ifstream::read() in C++ to read binary files efficiently, and also with the help of std::ifstream with the read() function. You can also use this method when dealing with non-text data such as images, videos, and audio files. It is suitable for both large and small files, as it provides reading binary files in C++ as a whole or in chunks. 

Example 1:

File name: sample.bin

Hello binary file
Cpp

Output:

Binary File Example1

In this code, it will open a binary file in C++, and to read the binary files, we use the std::istream::read() function till the end. It can print output as a whole line or in chunks. Then, the file is closed.

Get 100% Hike!

Master Most in Demand Skills Now!

Example 2:

File name: sample.bin

Hello, binary file!
Let’s read this file.
Cpp

Output:

Binary File Example2

In this code, a binary file is attached and opened. To read the binary files in C++, we use the std::istream::read() function till the end. It can print output as a whole line or in chunks. Then, the file is closed.

Reading a Binary File in Chunks

Reading a Binary File in Chunks refers to the process of sequentially loading fixed-size blocks of data from a binary file instead of reading the entire file at once. This approach is particularly useful when dealing with large files that may not fit entirely into memory or when you want to process data incrementally.

Why Read in Chunks?

  • Memory Efficiency: Reading in relatively small portions minimises memory demand as it only loads part of the file into memory.
  • Performance Optimisation: Chunked reading can enhance I/O performance against system or hardware specifications by adjusting buffer sizes to match.
  • Increment Processing: Read data piece-by-piece so that information can be processed as it is read, thereby accommodating streaming algorithms or real-time data processing.
  • Managing Unknown File Sizes: If the size of the file is unknown or very large, chunk reading gives a way to read the data in a safe manner and with controlled amounts.

Example:

File name: data.bin

Hello, Welcome to Intellipaat!

Cpp

Output:

reading for Binary Data in chunks

Advantages of Using ifstream::read for Binary Data in C++

  1. Independent of Locale and Formatting: ifstream::read is not affected by regional settings, nor is it influenced by formatting or locale settings. You will see the same behaviour on all platforms.
  2. Read Raw Bytes directly: ifstream::read in C++ will read raw bytes directly from a file memory; read has no rules for formatting or interpreting input. This is very important for binary formats, as the precise byte values are paramount.
  3. Faster and More Efficient: Since read does not parse, format, or perform other functions associated with formatted input like operator>>, it is faster and more efficient for reading binary files in C++.
  4. Exact Control of Sizes: Because you determine how many bytes to read, you have exact control over size when reading structured binary formats or fixed-size binary formats.
  5. Load Data into Structures: Because binary data can be read directly into C++ structures using reinterpret_cast, it is an easy way to load data into a specified memory layout.

Use Cases of Binary File Reading in Chunks

  1. Interfacing with Hardware or Devices:
    When reading raw binary data from either device files or sensors, or memory dumps for diagnostics or control.
  2. Loading Multimedia Files:
    Reading images, audio, or video files, which are all in binary formats, for processing or playback.
  3. Reading Serialised Data:
    Loading objects or data structures in binary format for efficient saving and loading.
  4. Working with Executable or Object Files:
    Reading or modifying compiled programs and libraries, which are also in binary files.
  5. Working with Custom or Proprietary File Formats:
    Reading binary data for other proprietary or application-specific files, such as assets for games or configuration files.

Practical Applications of Reading Binary Files in C++

  1. Embedded Systems and HW Interface:
    Reading for device control and diagnostics directly from firmware updates, sensor data logs, or binary dumps (memory).
  2. Game Development:
    Loading textures, models, maps, or other assets stored in binary formats for runtime efficiency.
  3. Data Serialisation and Deserialisation:
    Saving and restoring complex data structures or objects in binary format to store and retrieve data quickly.
  4. Image and Audio Processing:
    Reading raw image/audio data to edit it, analyse it, or convert the data into any format.
  5. Networking and Protocol Implementation:
    Parsing binary network packets or protocol messages received by sockets.

Conclusion 

Reading binary files in C++ requires special handling to correctly process raw data without formatting interference. The std::ifstream::read() method provides a reliable and efficient way to read binary data, either entirely or in chunks, making it ideal for handling multimedia files, serialised data, and hardware interfaces. By mastering this method, developers can effectively manage complex binary formats and optimise file I/O operations in their C++ applications.

Reading Binary Files in C++ – Explained with Examples -FAQs

Q1. How to use std::ifstream::read?

Use ifstream.read(buffer, size); to read binary data into a buffer.

Q2. How to store binary data in C++?

Store binary data in ‘std::vector‘ or write it directly to a file using ‘ofstream.’

Q3. How to open binary file in C++?

Use ‘std::ifstream file(“example.bin”, std::ios::binary);’ to open a binary file in C++ for reading and ‘std::ofstream’ for writing.

Q4. How do I read all bytes from a file?

Use std::vector and ‘ifstream.seekg(0, ios::end);’ to determine file size before reading.

Q5. How do you decode bytes to string?

Use ‘std::string(buffer, size);’ or convert using an appropriate encoding method like UTF-8.

Some Other Methods to Read a File Line by Line in C++

These articles present a solid introduction to the basic building blocks of C++.

C++ assignment operators – Details assignment in object-oriented design.

Substring in C++ – Applies substring logic in parsing and manipulation.

Pass objects to functions in C++ – Enables safe and efficient parameter handling.

Why are not variable length arrays part of the C++ standard? – Encourages safer dynamic array practices.

Getline in C++ – Enables robust text input in console apps.

Array decay or array to pointer conversion in C++ – Mentions std::array and std::vector as alternatives.

ifstream get in C++ – Highlights stream pointer behavior.

istream readsome in C++ – Optimizes performance for real-time input.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner