C++ binary file I/O to/from containers (other than char *) using STL algorithms

前端 未结 4 559
逝去的感伤
逝去的感伤 2021-01-06 22:52

I\'m attempting a simple test of binary file I/O using the STL copy algorithm to copy data to/from containers and a binary file. See below:

 1 #include 

        
4条回答
  •  猫巷女王i
    2021-01-06 23:39

    I have come up with a better design for binary I/O. The fundamental approach is to have three methods: size_on_stream, load_from_buffer, and store_to_buffer. These go into an interface class so that all classes that support binary I/O inherit it.

    The size_on_stream method returns the size of the data as transmitted on the stream. Generally, this does not include padding bytes. This should be recursive such that a class calls the method on all of its members.

    The load_from_buffer method is passed a reference to a pointer to a buffer ( unsigned char * & ). The method loads the object's data members from the buffer, incrementing the pointer after every member (or incrementing once after all the members).

    The store_to_buffer method stores data into the given buffer and increments the pointer.

    The client calls size_on_stream to determine the size of all the data. A buffer of this size is dynamically allocated. Another pointer to this buffer is passed to the store_to_buffer to store the object's members into the buffer. Finally, the client uses a binary write (fwrite or std::ostream::write) to transfer the buffer to the stream.

    Some of the benefits of this technique are: packing, abstraction and block I/O. The objects pack their members into the buffer. The process for writing into the buffer is hidden from the client. The client can use block I/O functions which are always more efficient than transferring individual members.

    This design is also more portable, as the objects can take care of the Endianess. There is a simple method for this, which is left up to the reader.

    I have expanded this concept to incorporate POD (Plain Old Data) types as well, which is left as an exercise for the reader.

提交回复
热议问题