Write Binary Files in C++

How to write binary files in C++

In this post, we will see how to write binary files in java.

The binary files are similar to the text files however the content in binary files is stored in binary format rather than simple text format.

The binary files can come in handy for storing complex objects such as structures, and classes.

This article discusses methods to write simple data such as string and complex objects such as structure objects to binary files in C++.

Opening a File in Binary Mode Using fstream Library

The fstream library in C++ provides all sorts of file handling operations. The open() method of the library is used to open the files in C++.

Let us see the definition of the open() method.

The open() method accepts,

  • Path of the file as a character array.
  • Mode to open the file.

The mode defines the operations that can be performed on the files. To open the binary file, you must include the ios_base::binary flag in concatenation to other mode flag variables.
You can read about all mode flags here.

Writing the Binary File Using the write() Function of fstream Library

The write() function in the fstream library writes the content of a stream to the file. The definition of the function is given below.

  • The function accepts a character array as the first argument. It represents the data that needs to be written to the file.
  • The second parameter ‘n’ represents the size of the stream. The ‘n’ characters are written from the character array to the file.

If the file is open in binary mode, the write() function writes the characters in the binary format.

Let us see the code that writes a string to a binary file.

Note that code uses the data() function of the string object. This is because the write() function accepts the character pointer rather than the string object. The data() function returns a pointer to an array that contains exactly the same elements as the string.

Also, you should try to close the file after using it by calling the close() function. However, even if you forget, the destructor closes the file after the fstream object goes out of scope.

Output:

This string is written to the binary file.

Writing the Binary File Using the put() Function of fstream Library

The fstream library inherits the put() function from the ostream library. The put() function writes one character at a time to a file. Therefore, you can use it to write characters to a binary file.

If you have multiple characters, an array of characters, or a stream, you will need a loop to write characters to a binary file using the put() function.

The definition of the put() function is given below.

After opening a file, you can simply call the put() function using the fstream object and pass the character to it. The character is written to the binary file.

Let us see the code.

Output:

This string is written to the binary file.

Writing the Binary File Using Insertion Operator (<<) Of fstream Library

Similar to writing to the text file, you can write to the binary file using the insertion operator (<<). This operator is overloaded in the ostream class and inherited in the fstream class.

You can use the insertion operator (<<) in a similar manner as you use for writing to the console. However, instead of cout you would use the fstream object.

Let us see the code.

Output:

This string is written to the binary file.

Writing the Structure Object to Binary File Using fstream Library

You can write the complex structure objects to the binary files using the write() function of the fstream library.

The only difference is that you can not pass the structure object directly to write() function. You have to cast the structure object reference to a character pointer. You can do so by a simple explicit cast in C++.

Let us see the code.

Output:

\C0VҚ\FC\00\00\00\00\00\00\00\00\00Mohtashim Nawaz\00\E0VҚ\FC\00\00\00\00\00\00\00\00\00male\00\00\00\00\00\00\00\00\00\00\00\00

Conclusion

Binary files store the data in binary format instead of storing it in text format. However, when opened in text editors, it generally shows data in text format.

While reading a binary file, it is mandatory that you know the structure of the file. Otherwise, the content may be illegible. That’s why the binary files are mostly used with images, network operations, etc.

That’s all about how to write binary files in C++.

Hope you have enjoyed reading the article. Stay tuned for more articles. Happy Learning!

Was this post helpful?

Related Posts

  • 19 May

    Get Type of Object in C++

    Table of ContentsWhy Should We Determine the Type of Object in C++: Dynamic DispatchingGet Type of Object in C++ConclusionWas this post helpful? C++ is an object-oriented language where we often interact with objects of different types. The object interaction becomes more interesting when we add runtime polymorphism to it. The runtime polymorphism, also known as, […]

  • 19 May

    Convert Vector to Array in C++

    Table of ContentsVectors and Arrays in C++Convert Vector to Arrays in C++Using the for loop to convert vector to array in C++Using the copy() function to convert vector to array in C++Using the transform() function to convert vector to array in C++Using the data() function to convert vector to array in C++Using the & operator […]

  • How to initialize an array in Constructor in C++
    23 April

    How to initialize an Array in Constructor in C++

    Table of ContentsArraysConstructors of a ClassWays to initialize an array in Constructor in C++Initialize an array in Constructor With std::fill()Initialize an array in Constructor Using for LoopInitialize an array in Constructor Using Member Initializer ListConclusionWas this post helpful? This article discusses methods of initializing an array in constructor in C++. Let us first discuss arrays […]

  • Write String to file in C++
    31 March

    Write String to File in C++

    Table of ContentsUsing the fstream Library to write String to File in C++Using the Insertion Operator (<<) With the fstream ObjectUsing the write() Function of the fstream LibraryUsing the fwrite() Function to write String to File in C++ConclusionWas this post helpful? The files are used to store the data permanently on a disk. This mitigates […]

  • Print Array in C++
    23 March

    Print Array in C++

    Table of ContentsIntroduction of ArraysDifferent Methods to Print an Array in C++print array in C++ by Traversing Indicesprint array in C++ Using for_each() Functionprint array in C++ Using Range-Based for Loopprint array in C++ Using Iteratorsprint array Using ostream_iterator() Function and copy() Functionprint array Using C++17 copy() Function and make_ostream_joiner() FunctionConclusionWas this post helpful? An […]

  • Print Vector C++
    23 March

    Print Vector in C++

    Table of ContentsPrint Vector in C++ Using IndicesPrint Vector in C++ Using Range-Based for LoopPrint Vector in C++ Using for_each() FunctionPrint Vector in C++ Using IteratorPrint Vector in C++ by Overloading the Insertion Operator (<<)Print Vector in C++ Using copy() FunctionConclusionWas this post helpful? This article discusses the vector and how to print vector in […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.