2014-05-15 3 views
0

아래의 코드를 사용하여 이진 파일에서 구조체를 읽습니다.여러 유형의 C++ 파일에서 구조체 읽기

struct A 
{ 
    int s; 
    char cname[20]; 
}; 

int main() { 
    A mystruct; 

    ifstream is; 
    is.open ("filename.txt", ios::binary); 

    is.read (&mystruct, sizeof(InpumystructtStruct)); 
    is.close(); 

    return 0; 
} 

파일에 나타나는 다양한 크기와 형태의 구조체 A, B 구조체 및 구조체 C의 이진 파일의 다중 구조체가있다하자. 시퀀스를 모두 알고 있다고 가정하면 시퀀스를 모두 읽으려는 것이 맞습니까?

struct A 
{ 
    int s; 
    char cname[20]; 
}; 
struct B 
{ 
    int s; 
};  
struct A 
{ 
    char cname[20]; 
}; 

int main() { 
    A mystructa; 
    B mystructb; 
    C mystructc; 

    ifstream is; 
    is.open ("filename.txt", ios::binary); 

    while(is.good() ) { 
     // determine struct to use 
     is.read (&mystruct/*put right type*/, sizeof(/*put right tupe*/)); 
    } 
    is.close(); 

    return 0; 
} 

답변

1

아니요, 작동하지 않습니다.

당신은 그들이 파일에 순차적으로 기록하고 알고있는 경우는 :

struct { 
    A a; 
    B b; 
    C c; 
} v; 

is.read (&v, sizeof v); 

그러나, 이것은 많은 문제가있다. 그 중 최소한의 것은 구조체 패딩, 크기가 int 라이터에서 사용되는 것입니다. 엔디안 문제 등

이러한 종류의 문제는 모두 JSON, XML 등의 범용 데이터 형식으로 처리됩니다.

은 약간 더 이식성, 당신이 쓴이 변화와 같은 문제이지만, 일하는 것이 이전 :

A mystructa; 
B mystructb; 
C mystructc; 

is.read (&mystructa, sizeof mystructa); 
is.read (&mystructb, sizeof mystructb); 
is.read (&mystructc, sizeof mystructc);