2011-04-22 62 views
0

该文件以二进制模式打开,第一个变体出现异常,第二个不是。 如何使用ifstream直接读取我的目标对象?请帮帮我。 这里是我的代码:如何用ifstream读入对象成员?

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)); 
} 
} 
+2

看来你是写入到内存的任意位置。这只是运气,你的第二个变体正在工作。尝试fp-read(&this-> length,sizeof(length))。 – beduin 2011-04-22 10:55:18

+0

@Alexander:这种方法似乎不是一个好主意。你必然会遇到编译器实现相关的差异。如果您想以便携和安全的方式进行序列化,请考虑使用[Boost.Serialization](http://boost.org/doc/libs/1_46_1/libs/serialization/doc/index.html)。 – 2011-04-22 11:04:45

+0

@ Space_C0wb0y我的意思不是粗鲁,而是将他介绍给'Boost'就像是带走他的弹弓(这样他就不会伤害自己),而是给他一个大炮。 – cnicutar 2011-04-22 11:08:12

回答

1

试试这个:

fp->read(&this->length,sizeof(this->length)); 

(char *)this->length意味着:

  • 得到一些号码,你只是做了
  • 写入到存储位置
  • 希望最好的
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; 
}