简体   繁体   English

了解C ++ Vecotor

[英]fread to C++ Vecotor

I have a binary file, 我有一个二进制文件

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

Which can be successfully read using fread() with the following C code 可以使用fread()和以下C代码成功读取

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

But when I read file to C++ vector, the result is wrong 但是当我将文件读取到C ++向量时,结果是错误的

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

Is there anything wrong with above code ?. 上面的代码有什么问题吗?

table.size() returns the number of elements in the std::vector , not the number of bytes. table.size()返回std::vector的元素数,而不是字节数。 You still need to multiply that by the size of each element, just like you do in the C code. 就像在C代码中一样,您仍然需要将其乘以每个元素的大小。

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

Your fread should be:- 您的fread应该是:

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

Both appear to be wrong (although the C version looks like it will work). 两者似乎都是错误的(尽管C版本看起来可以工作)。

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

Try these: 试试这些:

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