繁体   English   中英

了解C ++ Vecotor

[英]fread to C++ Vecotor

我有一个二进制文件

FILE *fp;
fp = fopen("file_name.data", "rb");

可以使用fread()和以下C代码成功读取

int S = 8;
int *table = (int*)malloc(S*sizeof(int));
fread(table, S*sizeof(int), 1, fp);

但是当我将文件读取到C ++向量时,结果是错误的

vector<int> table;
table.resize(S);
fread(&table[0],table.size(), 1, fp);

上面的代码有什么问题吗?

table.size()返回std::vector的元素数,而不是字节数。 就像在C代码中一样,您仍然需要将其乘以每个元素的大小。

fread(&table[0],table.size()*sizeof(int), 1, fp);

您的fread应该是:

fread (&table[0], sizeof(vector<int>::value_type), table.size(), fp);
// OR
fread (&table[0], sizeof(int), table.size(), fp);

两者似乎都是错误的(尽管C版本看起来可以工作)。

请参阅: http : //www.tutorialspoint.com/c_standard_library/c_function_fread.htm

试试这些:

int S = 8;
int *table = (int*)malloc(S*sizeof(int));
fread(table, sizeof(int), S, fp);

vector<int> table;
table.resize(S);
fread(&table[0], sizeof(int), table.size(), fp);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM