2016-06-08 58 views
0

我解析一個位圖頭文件(只是爲了好玩),而且我無法將數據放入結構體中。這是我的代碼:把數組的部分放入結構體

#include <iostream> 
#include <fstream> 

using namespace std; 

struct bmp_header { 
    char16_t id; 
    int size; 
    char16_t reserved1; 
    char16_t reserved2; 
    int offset_to_pxl_array;  
} bmp_header; 

int main(int argc, char *argv[]) { 
    if (argc < 2) { 
     cout << "No image file specified." << endl; 
     return -1; 
    } 
    ifstream file(argv[1], ios::in|ios::binary|ios::ate); 
    streampos f_size = file.tellg();  
    char *memblock; 

    if (!file.is_open()) { 
     cout << "Error reading file." << endl; 
     return -1; 
    } 

    memblock = new char[f_size]; 

    //Read whole file 
    file.seekg(0, ios::beg); 
    file.read(memblock, f_size); 
    file.close(); 

    //Parse header 
    //HOW TO PUT FIRST 14 BYTES OF memblock INTO bmp_header? 

    //Output file 
    for(int x = 0; x < f_size; x++) { 
     cout << memblock[x]; 
     if (x % 20 == 0) 
      cout << endl; 
    } 
    cout << "End of file." << endl; 

    delete[] memblock; 

    return 0; 
} 

如何把memblock的第14個元素融入bmp_header?我一直在嘗試在網絡上進行一些搜索,但對於這樣一個簡單的問題,大多數解決方案似乎都有點複雜。

回答

0

要做到這一點最簡單的方法是使用std::ifstream及其read成員函數:

std::ifstream in("input.bmp"); 
bmp_header hdr; 
in.read(reinterpret_cast<char *>(&hdr), sizeof(bmp_header)); 

有一點需要注意,雖然:編譯器將bmp_headeralign成員變量。因此你必須防止這種情況。例如。在gcc你說__attribute__((packed))做到這一點:

struct bmp_header { 
    char16_t id; 
    int size; 
    char16_t reserved1; 
    char16_t reserved2; 
    int offset_to_pxl_array;  
} __attribute__((packed)); 
+2

還有另外一個警告 - 這將僅在小端架構工作。在一個大端的程序中,你還需要處理字節交換。 –

+0

謝謝你的回答。有更容易的方法嗎? – Pelle