• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Reading and Writing std::vector to a file

Resolved: Reading and Writing std::vector to a file

0
By Isaac Tonny on 15/03/2023 Issue
Share
Facebook Twitter LinkedIn

In this post, we will see how to resolve Reading and Writing std::vector<struct> to a file

Question:

I need to write a vector to a file, and then read it back into a vector.
The vector contains hundreds, possibly thousands, of structs which each contain 2 different structs.
I thought that the best way to do it would be to get the pointer with MyVector.data() and somehow write the data using that.
Just in case here’s a diagram of the vector:
and so on.
I tried multiple methods, such as ofstream.write() and fwrite(), but none of them worked.
This gives me an error of:

binary ‘=’: no operator found which takes a right-hand operand of type ‘Frame’ (or there is no acceptable conversion)


Best Answer:

std::ostreambuf_iterator writes character data to the output stream whenever it is assigned a single character via its operator=. Since you are specifying char as the CharT template parameter of std::ostreambuf_iterator, its operator= expects a char value to be assigned to it (ie, when used to write data from a std::vector<char>, std::string, etc), but you are trying to write Frame objects from a std::vector<Frame> instead. IOW, since you are trying to write Frame objects where char values are expected, that is why you are getting the conversion error on operator=.
You have a similar issue with reading in using std::istreambuf_iterator, too. It is meant for reading in character data (via its operator*), not structured data.
For what you are attempting to do, you need to use std::ostream_iterator (and std::istream_iterator) instead. You will simply have to define an overloaded operator<< (and operator>>) for Frame to write/read its member data to/from a std::ostream/std::istream as needed.
Try this:

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com

c++ file-handling read-write struct vector
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Why reference in pointer array doesn’t have data?

24/03/2023

Resolved: EntityFramework creates/runs migrations using parameterless DataContext instance

24/03/2023

Resolved: Visual Studio 2022 crashes when using breakpoints

24/03/2023

Comments are closed.

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.