2014-09-02 175 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]); 
    } 
}