2011-04-22 2 views
0

파일이 바이너리 모드로 열렸습니다. 첫 번째 변형은 예외이며, 두 번째 변형은 예외입니다. ifstream을 사용하여 mhead 개체를 직접 읽을 수 있습니까? 도와주세요. 다음은 내 코드입니다 :개체 구성원으로 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

+0

@ Alexander :이 접근법은 좋은 생각처럼 보이지 않습니다. 당신은 컴파일러 구현 의존적 인 차이에 비틀 거리게됩니다. 직렬화를 이식 가능하고 안전하게 수행하려면 [Boost.Serialization] (http://boost.org/doc/libs/1_46_1/libs/serialization/doc/index.html)을 사용하는 것이 좋습니다. –

+0

@ Space_C0wb0y 나는 무례 함을 의미하지는 않지만 그를 '부스트 (Boost)'로 소개하는 것은 그의 새총을 치워 버리고 (그래서 자신을 다치게하지는 않을 것입니다) 대신 대포를주는 것과 같습니다. – cnicutar

답변

1

이 시도 :

(char *)this->length에 쓰기
fp->read(&this->length,sizeof(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; 
} 
관련 문제