2014-09-02 2 views
0

C++에서 fstream으로 바이트 파일을 읽으려고합니다 (목표 : 바이너리 데이터 형식 비 직렬화). DAT 파일은 HxD 진수 편집기에서 다음과 같은 (bytes.dat) 같습니다cpp 바이트 파일 읽기

bytefile

을하지만 char 배열로 이진 파일을 읽을 때 뭔가 잘못 .. 여기 MWE입니다 :

#include <iostream> 
#include <fstream> 
using namespace std; 

int main(){ 
    ofstream outfile; 
    outfile.open("bytes.dat", std::ios::binary); 
    outfile << hex << (char) 0x77 << (char) 0x77 << (char) 0x77 << (char) 0x07 \ 
    << (char) 0x9C << (char) 0x04 << (char) 0x00 << (char) 0x00 << (char) 0x41 \ 
    << (char) 0x49 << (char) 0x44 << (char) 0x30 << (char) 0x00 << (char) 0x00 \ 
    << (char) 0x04 << (char) 0x9C; 
    ifstream infile; 
    infile.open("bytes.dat", ios::in | ios::binary); 
    char bytes[16]; 
    for (int i = 0; i < 16; ++i) 
    { 
    infile.read(&bytes[i], 1); 
    printf("%02X ", bytes[i]); 
    } 
} 

는하지만이 (컴파일는 MinGW)를 cout을에 보여줍니다

> g++ bytes.cpp -o bytes.exe 

> bytes.exe 

6A 58 2E 76 FFFFFF9E 6A 2E 76 FFFFFFB0 1E 40 00 6C FFFFFFFF 28 00 

메신저 뭔가 잘못하고. 일부 배열 항목에 4 바이트가있을 수 있습니까?

+1

선언' 'unsigned char' 배열을 만들거나'bytes [i]'를'unsigned char'으로 형 변환합니다. –

+0

tnx 이렇게하면 긴 FFFFFF 문제가 해결됩니다. 그러나 값은 16 진수 편집기에있는 값이 아닙니다. – Walter

+3

'operator << 대신에 [연산자] 대신 ['outfile.write()'] (http://en.cppreference.com/w/cpp/io/basic_ostream/write)를 사용하십시오 '이진 데이터를 저장합니다. –

답변

4
  • 이진 데이터 (이진 파일 형식 등)로 작업하는 경우 부호없는 정수 형식을 사용하여 부호 확장 변환을 피하는 것이 좋습니다.
  • 이진 데이터를 읽고 쓸 때 권장되는대로 stream.readstream.write 함수를 사용하는 것이 좋습니다 (블록 단위로 더 읽고 쓰는 것이 더 좋습니다). 당신이 파일의 데이터를 (std::vector 기본값)로드해야하는 경우
  • 당신이 저장에 필요한 경우 고정 된 이진 데이터는 std::array 또는 std::vector 사용

고정 코드 : 같은 bytes`

#include <iostream> 
#include <fstream> 
#include <vector> 
using namespace std; 

int main() { 
    vector<unsigned char> bytes1{0x77, 0x77, 0x77, 0x07, 0x9C, 0x04, 0x00, 0x00, 
           0x41, 0x49, 0x44, 0x30, 0x00, 0x00, 0x04, 0x9C}; 
    ofstream outfile("bytes.dat", std::ios::binary); 
    outfile.write((char*)&bytes1[0], bytes1.size()); 
    outfile.close(); 

    vector<unsigned char> bytes2(bytes1.size(), 0); 
    ifstream infile("bytes.dat", ios::in | ios::binary); 
    infile.read((char*)&bytes2[0], bytes2.size()); 
    for (int i = 0; i < bytes2.size(); ++i) { 
     printf("%02X ", bytes2[i]); 
    } 
}