[英]How to read with ifstream into object member?
The file opened in binary mode, the first variation gives exception, the second one is not. 在二进制模式下打开的文件,第一个版本例外,第二个则没有。 How can I read directly to my mhead object with ifstream? 如何使用ifstream直接读取我的mhead对象? Please help me. 请帮我。 Here is my code: 这是我的代码:
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));
}
}
Try this: 尝试这个:
fp->read(&this->length,sizeof(this->length));
Writing to (char *)this->length
means: 写入(char *)this->length
表示:
If read was successful readlong
return true. 如果读取成功,则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) )
};
}
Or (I suggest this one): 或者(我建议这一点):
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.