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++.

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

The std::ifstream::read() function 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.

Using std::ifstream::read() for Binary Files in C++

To read the raw binary data efficiently in C++, you can use 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 files as a whole or in chunks. 

Example:

File name: sample.bin

Hello binary file
Cpp

Output:

Binary File Example1

In this code, a binary file is attached and opened. 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!

Another Example:

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, 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.

Conclusion 

The std::ifstream::read() method in C++ is used for reading binary files in C++. This method handles the raw data easily and is also useful for non-text data such as images, videos, and audio files. So, by understanding this method with examples, you can easily read binary files in C++.

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

  • eof() in C++
  • getline() Function in C++
  • basic_istream::operator>> in C++
  • istream::readsome() in C++
  • std::ifstream::get() in C++

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