【问题标题】:fread struct with vector from binary file gives Access violation reading errorfread struct with vector from binary file 给出访问冲突读取错误
【发布时间】:2022-10-14 22:26:51
【问题描述】:

我正在尝试将带有向量的结构读写到 C++ 中的文件中。我收到读取冲突错误,为什么会这样,我该如何解决?这是代码。

#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;
}

附带说明:如果我将结构 A 更改为

struct A
{
    int int_vector;
};

该程序按预期工作而没有错误,因此导致问题的向量存在一些问题。

【问题讨论】:

  • 您不能直接读/写包含指针的对象
  • 您需要序列化您的数据。实际的向量对象根本不包含数据,只有几个指针等。
  • fwrite(&amp;a1, sizeof(A), 1, outfile); -- 令人惊讶的是,如此多的新程序员相信这对任何A 类型都可以正常工作 -- StackOverflow 中充斥着同样的问题。就好像这种错误的数据写入方式来自许多人似乎正在使用的书。

标签: c++ fread access-violation


【解决方案1】:

如您所知,std::vector 是动态的,它只包含一个指向堆上数据的指针。 sizeof(std::vector) 是一个常数值,因此您不能将其写入文件然后再将其读回。

您需要的是序列化,您可以在 github 上找到一些很棒的开源库,它们可以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 2012-05-13
    • 1970-01-01
    相关资源
    最近更新 更多