2014-09-02 143 views
0

我试图用C++读取一个字节文件(目标:二进制数据格式反序列化)。 DAT文件看起来像下面的Hex Editor(bytes.dat):cpp字节文件读取

bytefile

但读二进制文件转换成字符数组出问题的时候..这里是一个兆瓦:

#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]); 
    } 
} 

但是这显示了COUT(MinGW的编译):

> 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

申报'bytes'如一个'unsigned char'数组或''将字节'我''转换为'unsigned char'。 – 2014-09-02 13:54:38

+0

tnx解决了长时间的FFFFFF问题。但是这些值不是十六进制编辑器中的内容 – Walter 2014-09-02 13:55:52

+3

使用['outfile.write()'](http://en.cppreference.com/w/cpp/io/basic_ostream/write)而不是'operator << '存储二进制数据。 – 2014-09-02 13:56:25

回答

4
  • 使用二进制数据(二进制文件格式等)时,最好使用无符号整数类型以避免符号扩展转换。
  • 正如在读取和写入二进制数据时所推荐的,最好使用stream.readstream.write函数(它也更好地读写块)。
  • 如果需要存储固定的二进制数据使用std::arraystd::vector,如果需要加载从文件数据(std::vector是默认值)

固定码:

#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]); 
    } 
}