2014-02-14 3 views
0

을 읽을및 표준 : 나는 구조를 가지고 C++

struct details 
{ 
    std::string username; 
    std::string password; 
    bool isActive; 
}; 

struct details v_Details; 

내가 읽은 다음 파일에 이러한 데이터를 작성하고자하는 코드의 다른 지점에서 세부 사항을 저장하는 수단으로 사용됩니다. 나는 그것의 작업을

std::ofstream out_file; 
out_file.open ("db.dat" , ios::out | ios::binary) 
out_file.write((char*)&v_details , sizeof (struct details)) 

을 할 것으로 보인다하지만 난 단지 사용자 이름과 암호를 읽어 데이터를 읽을하려고 할 때 다음 충돌 표준 : 쓰기를 사용하여 시도했다. 코드의

내 읽기 부분은 도움이에 나에게 수정 프로그램을 제공 할 수

std::ifstream in_file; 
in_file.open (fileName.c_str() , std::ifstream::in); 

std::string readFileLine = "\0"; 

if (in_file.is_open()) 
{ 
    do 
    { 
     in_file.read ((char*)&details , sizeof(details)); 
     cout << "\nDEBUG message-> " << __FILE__ <<" : " << __func__ << " : " << __LINE__ << " : Read - "<< details.username << " " << details.password << " " << isActive ; 
    }while (!in_file.eof()); 

in_file.close(); 
} 

누구나 다음과 같다.

+0

'std :: string' 인스턴스의 내용은 실제로 그것이 감싸는 문자열이 아니라 문자열과 길이에 대한 포인터 일 것임을 기억해야합니다. [marshalling] (http://en.wikipedia.org/wiki/Marshalling_%28computer_science%29) 및 [serialization] (http://en.wikipedia.org/wiki/Serialization)에 대해 읽어야합니다. –

+1

[Boost serialization library] (http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/index.html)에 대해서도 읽어보십시오. 이렇게하면 이런 일을 처리하는 데 도움이됩니다. –

답변

0

개체를 직접 쓸 수없고 고정 된 크기가 아닌 멤버가있을 때 모든 개체를 올바르게 저장할 것으로 기대할 수 없습니다. 배열이 인 경우이 방법을 사용할 수 있습니다.

이 상황을 감안할 때, 내가 수동으로 다음 username 문자 쓰기, 첫 username의 길이와 같은 세부 사항을 작성합니다 그래서 내가 이름의 길이를 읽고 파일에서 문자의 수를 읽을 수 읽는 동안.

관련 문제