文件以二进制模式打开,第一个变体给出异常,第二个变量不给出异常。 如何使用ifstream直接读取我的mhead对象?请帮我。 这是我的代码:
class mhead {
public:
long length;
void readlong(std::ifstream *fp);
}
void mhead::readlong(std::ifstream *fp)
{
//this one is not work
fp->read((char*)this->length,sizeof(this->length));
//this is working
long other;
fp->read((char*)other,sizeof(other));
}
}
答案 0 :(得分:1)
试试这个:
fp->read(&this->length,sizeof(this->length));
写(char *)this->length
表示:
答案 1 :(得分:0)
如果读取成功readlong
则返回true。
class mhead
{
public:
long length;
bool readlong(std::istream &is)
{
is.read(reinterpret_cast<char *>( &this->length ), sizeof(long) );
return ( is.gcount() == sizeof(long) )
};
}
或(我建议这个):
istream & operator >> ( istream &is, mhead &_arg )
{
long temp = 0;
is.read(reinterpret_cast<char *>( &temp ), sizeof(long) );
if ( is.gcount() == sizeof(long) )
_arg.length = temp;
return is;
}