【发布时间】: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(&a1, sizeof(A), 1, outfile);-- 令人惊讶的是,如此多的新程序员相信这对任何A类型都可以正常工作 -- StackOverflow 中充斥着同样的问题。就好像这种错误的数据写入方式来自许多人似乎正在使用的书。
标签: c++ fread access-violation