I'm trying to read and write a struct with vectors to a file in C . I'm getting read violation error, why is that and how can I fix it? Here's the code.
#pragma warning(disable : 4996)
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace std;
struct A
{
vector<int> int_vector;
};
int main()
{
A a1 = A();
a1.int_vector.push_back(3);
FILE* outfile = fopen("save.dat", "w");
if (outfile == NULL)
{
cout << "error opening file for writing " << endl;
return 1;
}
fwrite(&a1, sizeof(A), 1, outfile);
fclose(outfile);
struct A ret;
FILE* infile;
infile = fopen("save.dat", "r");
if (infile == NULL)
{
cout << "error opening file for reading " << endl;
return 1;
}
while (fread(&ret, sizeof(A), 1, infile))
{
}
fclose(infile);
cout << ret.int_vector.at(0) << endl;
return 0;
}
As a side note: If I change the struct A to
struct A
{
int int_vector;
};
the program works as expected without errors, so there's something about the vector which is causing the problem.
CodePudding user response:
std::vector
as you know, is dynamic, it simply contains a pointer to the data located on the heap. The sizeof(std::vector) is a constant value, you could not just write it to a file then read it back for that reason.
What you need is serialization, there are some awesome open source library that you could find on github which will solve your problem.