【问题标题】:How to read with ifstream into object member?如何使用 ifstream 读取对象成员?
【发布时间】:2011-04-22 10:42:04
【问题描述】:

以二进制模式打开的文件,第一个变体给出异常,第二个没有。 如何使用 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));
}
}

【问题讨论】:

  • 似乎您正在写入内存中的某个随机位置。只是运气,您的第二个变体正在工作。试试 fp-read(&this->length, sizeof(length))。
  • @Alexander:这种方法似乎不是一个好主意。您一定会偶然发现依赖于编译器实现的差异。如果您想以可移植且安全的方式进行序列化,请考虑使用Boost.Serialization
  • @Space_C0wb0y 我并不是要无礼,但将他介绍给Boost 就像拿走他的弹弓(这样他就不会伤害自己)并给他一门大炮。
  • @cnicutar:实际上,将他介绍给 Boost 是给他一个起点,他可以从中学习如何编写好的 C++。 Boost 文档中的大多数示例都是非常好的示例。

标签: c++


【解决方案1】:

试试这个:

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

写信给(char *)this->length 表示:

  • 获取一些你刚刚编的号码
  • 写入该内存位置
  • 希望一切顺利

【讨论】:

    【解决方案2】:

    如果读取成功 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多