C++ / C++ File I/O and Streams

Performing Binary File I/O in C++

This tutorial will teach you how to perform binary file I/O in C++. Binary file I/O allows for a more efficient and precise way to store and retrieve data.

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers file handling and working with streams in C++.

Performing Binary File I/O in C++

1. Introduction

In this tutorial, we will learn how to perform binary file Input/Output (I/O) operations in C++. Binary file I/O allows for a more efficient and precise way to store and retrieve data. By the end of this tutorial, you will be able to read from and write to binary files using C++.

Prerequisites: Basic knowledge of C++ programming and familiarity with basic file I/O operations.

2. Step-by-Step Guide

Binary files store data in a binary format, which is the same format in which the data is held in memory. Unlike text files, binary files are not human-readable. When we say binary files, it generally refers to data files that contain data, not readable characters.

To read and write in binary mode, the file stream objects have the member function open(), which accepts an additional argument for mode. The modes are defined in the ios class, which is the base class for all the file streams in C++. To open a file in binary mode, we use the ios::binary mode.

Reading from a Binary File

To read from a binary file, follow these steps:

  1. Open the file in binary mode.
  2. Read the data from the file.

Writing to a Binary File

To write to a binary file, follow these steps:

  1. Open the file in binary mode.
  2. Write the data to the file.

3. Code Examples

Example 1: Writing to a Binary File

#include <fstream>
#include <iostream>

int main() {
    int number = 12345;
    std::ofstream outputFile;

    // Open the file in binary mode
    outputFile.open("output.bin", std::ios::binary);

    // Write to the file
    outputFile.write((char*)&number, sizeof(number));

    outputFile.close();
    return 0;
}

This program writes an integer to a binary file. outputFile.write((char*)&number, sizeof(number)); writes the binary representation of number to the file.

Example 2: Reading from a Binary File

#include <fstream>
#include <iostream>

int main() {
    int number;
    std::ifstream inputFile;

    // Open the file in binary mode
    inputFile.open("output.bin", std::ios::binary);

    // Read from the file
    inputFile.read((char*)&number, sizeof(number));

    std::cout << "The number is: " << number << std::endl;

    inputFile.close();
    return 0;
}

This program reads an integer from a binary file. inputFile.read((char*)&number, sizeof(number)); reads the binary data from the file into number.

Expected Output for Example 2:

The number is: 12345

4. Summary

In this tutorial, we learned how to perform binary file I/O in C++. We learned how to write to and read from binary files using the write() and read() member functions of the fstream library.

5. Practice Exercises

For further practice, try the following exercises:

  1. Write a program to write an array of integers to a binary file and then read it back.
  2. Write a program to write a custom object to a binary file and then read it back.

Remember, practicing and experimenting is the key to learning programming. Good luck!

Additional Resources

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help