0
C++에서 fstream으로 바이트 파일을 읽으려고합니다 (목표 : 바이너리 데이터 형식 비 직렬화). DAT 파일은 HxD 진수 편집기에서 다음과 같은 (bytes.dat) 같습니다cpp 바이트 파일 읽기
을하지만 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 바이트가있을 수 있습니까?
선언' 'unsigned char' 배열을 만들거나'bytes [i]'를'unsigned char'으로 형 변환합니다. –
tnx 이렇게하면 긴 FFFFFF 문제가 해결됩니다. 그러나 값은 16 진수 편집기에있는 값이 아닙니다. – Walter
'operator << 대신에 [연산자] 대신 ['outfile.write()'] (http://en.cppreference.com/w/cpp/io/basic_ostream/write)를 사용하십시오 '이진 데이터를 저장합니다. –