Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fread struct with vector from binary file gives Access violation reading error

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading