ifstream 二进制文件错误
ifstream binary file wrong
我必须读取结构如下的二进制文件:
n 1 字节,n 字节,4 字节等
这是我的代码:
char length;
file >> length;
char c[ 64 ];
file.read( c, length );
c[ length ] = 0;
int ver;
file >> ver;
问题:ver 始终为 0(在 ~2500 个文件上),但它不应该是。 length 输出正确的值,c 也是。在调用 read 之后,告诉 returns -1.
你说
1 byte for n, n bytes, 4 bytes, etc
我建议使用:
char length;
file.read(&length, 1);
// Check the value of length and make sure you have enough space.
if ( length > 63 )
{
// Deal with error condition
}
char c[ 64 ];
file.read( c, length );
c[ length ] = 0;
// Use a type that is know to be 4 bytes wide.
// Use read() instead of formatted input.
int32_t ver;
file.read(reinterpret_cast<char*>(&ver), sizeof(ver));
我必须读取结构如下的二进制文件: n 1 字节,n 字节,4 字节等
这是我的代码:
char length;
file >> length;
char c[ 64 ];
file.read( c, length );
c[ length ] = 0;
int ver;
file >> ver;
问题:ver 始终为 0(在 ~2500 个文件上),但它不应该是。 length 输出正确的值,c 也是。在调用 read 之后,告诉 returns -1.
你说
1 byte for n, n bytes, 4 bytes, etc
我建议使用:
char length;
file.read(&length, 1);
// Check the value of length and make sure you have enough space.
if ( length > 63 )
{
// Deal with error condition
}
char c[ 64 ];
file.read( c, length );
c[ length ] = 0;
// Use a type that is know to be 4 bytes wide.
// Use read() instead of formatted input.
int32_t ver;
file.read(reinterpret_cast<char*>(&ver), sizeof(ver));