2017-12-07 21 views
0

나는 int의 간단한 벡터를 가지고 있으며 이진 파일에 작성하려고합니다. 예를 들어 :C++ 바이너리 파일 - ints - strange 동작 작성

00000000: 050a 0f14 0a 

그게 전부 확인! :

다음
#include <fstream> 
#include <vector> 

int main() { 
    std::vector<uint32_t> myVector{5, 10, 15, 20 }; 
    // write vector to bin file 
    std::ofstream outfile("./binary_ints.data", std::ios_base::binary|std::ios::trunc); 
    std::copy(myVector.begin(), myVector.end(), std::ostreambuf_iterator<char>(outfile)); 
    outfile.close(); 
    return 0; 
} 

내가 16 진수 모드에서 파일 "binary_ints.data"를 검사하는 경우,이이 myVector이 데이터가있는 경우

그러나 :

std::vector<uint32_t> myVector{3231748228}; 

그런 다음, 저장된 진수가 이상해 : 무슨 일 이죠 3231748228.

16 진수
00000000: 840a 

(84)는 지능과 일치하지 않습니다 이리? 감사합니다. .

+2

'std :: copy'는 한 요소를 여러 개의 새로운 요소로 변환하지 않으며'std :: ostreambuf_iterator '도 변환하지 않습니다. – chris

+2

'int' 값이> 255 인 경우 어떤 일이 일어나는지 몇 가지 실험을 해보았을 것입니다. – PaulMcKenzie

+2

실제로 벡터 데이터의 일부인 것 이외의 추가 개행 문자가 나오는 곳이 궁금합니다. 프로그램은 벡터 데이터 뒤에 하나를 쓰면 안됩니다. –

답변

3

std::copy() 호출 중에 std::vector<uint32_t>의 각 값이 char으로 해석되는 것이 문제입니다. 3231748228은 16 진수로 ‭C0A09084으로 표시됩니다. std::copy()uint32_t 값을 취하고이 값을 프로세서의 0x84 인 1 바이트로 자릅니다. 쓰기 바이트 후 0x84 파일 바이트 0x0anew line character에 해당하는 추가됩니다.

가능한 용액 std::copy() 대신 ofstream::write()을 사용하는 것이다

#include <fstream> 
#include <vector> 

int main() { 
    std::vector<uint32_t> myVector{3231748228 }; 
    // write vector to bin file 
    std::ofstream outfile("./binary_ints.data", std::ios_base::binary|std::ios::trunc); 

    outfile.write (
     (char*)(myVector.data()), 
     myVector.size() * sizeof (decltype (myVector)::value_type)); 

    outfile.close(); 
    return 0; 
} 

참고 decltype() 용도. sizeof (uint32_t)을 쓰는 것만으로도 동일한 효과가 나타날 수 있지만 decltype()을 사용하면 myVector 값 유형을 변경하더라도 코드가 올바로 유지 될 수 있습니다.