The script used by me to write a vector of structure cameras to a binary file:
ofstream file;
file.open(cameraParamFile.c_str(), ios_base::binary);
const char* pointer = reinterpret_cast<const char*>(&cameras[0]);
size_t bytes = cameras.size() * sizeof(cameras[0]);
file.write(pointer, bytes);
This is what the structure looks like:
struct CV_EXPORTS CameraParams
{
CameraParams();
CameraParams(const CameraParams& other);
const CameraParams& operator =(const CameraParams& other);
Mat K() const;
double focal; // Focal length
double aspect; // Aspect ratio
double ppx; // Principal point X
double ppy; // Principal point Y
Mat R; // Rotation
Mat t; // Translation
};
and here is the vector declaration:
vector<CameraParams> camerasTest
Now when I try reading from this file, I am unable to do it (still a newbie to c++). It gives me error saying no matching function for call to 'std::basic_ifstream::read(std::vector, size_t&)'|*.
Here is my attempt:
vector<CameraParams> camerasTest;
ifstream inf1;
inf1.open(cameraParamFile.c_str(), ios::binary | ios::in);
inf1.read(&camerasTest, bytes));
I think this is an issue related to typecasting, or incorrect arguments. Can someone please point out the right way?
I tried reading the below mentioned link but couldn't make much sense: Write and load vector of structs in a binary file c++
EDIT
As suggested in the comments I tried implementing custom reader and writer using the above link. Here are function written by me. It still does not work.
void writeStruct(ostream& out, const vector<CameraParams> &vec)
{
typename vector<CameraParams>::size_type size = vec.size();
os.write((char*)&size, sizeof(size));
os.write((char*)&vec[0], vec.size() * sizeof(CameraParams));
}
void readStruct(istream& is, vector<CameraParams> &vec)
{
typename vector<CameraParams>::size_type size = 0;
is.read((char*)&size, sizeof(size));
vec.resize(size);
is.read((char*)&vec[0], vec.size() * sizeof(CameraParams));
}
When I try to print the values using the above reading function using the below script:
vector<CameraParams> cameraTest;
std::ifstream in(cameraParamFile.c_str(), std::ios::in | std::ios::binary);
readCameraParamsVector(in, cameraTest);
in.close();
cout << cameraTest[0].R;
cout << "\n";
cout << cameras[0].R;
It starts giving me a run time error saying process terminated with status -1073741819
EDIT 2 As mentioned in the comments why I couldn't use the answer mentioned in the link Write and load vector of structs in a binary file c++ ? I have already mentioned in EDIT 1 that I wrote a write and read function using that link but still gives me the error as shown above.