How to mimic C#’s BinaryReader / BinaryWriter in C++

Binary Reader Writer C++

Writing primitive types and structs into disk

I was looking for a way to write floats/ints/strings to a file, then read them as floats/ints/strings. I needed it because of the 2D Game Editors I built. I wanted to be able to generate a character or map file, that can be read, updated, saved, etc. On top of the primitive types, I needed to also write a whole struct and be able to read it in 1 line of code as a struct (not have to read each property of the struct 1 by 1). That way the Game Engine can load the characters/maps and get the game rolling! Basically read and write as ios::binary. I couldn’t find anything that does that for C++. So I ended up writing it myself, thought I would share it :)  
A couple of quick notes:
  • You can ignore the “BM” part, it was just a prefix for my game editor. I like to prefix file names to that I can type “BM…” and will see every single class that I wrote, without having to refer to the namespace.
  • The BMLogging is just a helper class that logs strings as needed.

Here’s how you would use it to WRITE:


Here’s how you would use it to READ:


You could even write/read a whole struct in 1 line:

  Hope that helps, please don’t hesitate to provide feedback or drop a comment!

Leave a Reply

Your email address will not be published. Required fields are marked *