I'm looking for a way to write floats/ints/strings to a file and read them as floats/ints/strings. (basically read/write as ios::binary).
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
I ended up writing it myself. Just wanted to share it with others.
It might not be optimized, but I had some difficulties finding C++ code that mimics C#'s BinaryReader & BinaryWriter classes. So I created one class that handles both read and write.
Quick things to note:
1) "BM" is just a prefix for my classes.
2) BMLogging is a helper class that simply does:
So you can ignore the calls to BMLogging, I kept them to highlight the cases where we could warn the user.
Here's the code:
EDIT: I replaced all the read/write methods above with these: (updated the usage code as well)
This is how you would use it to WRITE:
Here's how you would use it to READ:
EDIT 2: You could even write/read a whole structure in 1 line:
Hope my code is clear enough.
I subclassed
ifstream
andofstream
:ibfstream
andobfstream
. I made a class that would detect the endianness of the machine I was compiling/running on. Then I added a flag foribfstream
andobfstream
that indicated whether bytes in primitive types should be flipped. These classes also had methods to read/write primitive types and arrays of such types flipping the byte order as necessary.I was often working on a little-endian machine and wanting to write big-endian files or vice versa. This was used in a program tht did a lot of I/O with 3D graphics files of various formats.
I subclassed
ifstream
andofstream
:ibfstream
andobfstream
. I made a little helper class that would detect the endianness of the machine I was compiling/running on. Then I added a flag foribfstream
andobfstream
that indicated whether bytes in primitive types should be flipped. These classes also had methods to read/write primitive types and arrays of such types flipping the byte order as necessary. Finally, I setios::binary
for these classes by default.I was often working on a little-endian machine and wanting to write big-endian files or vice versa. This was used in a program that did a lot of I/O with 3D graphics files of various formats.