2015-04-29 92 views
0

我目前正在閱讀一個二進制文件,我知道結構,我正試圖放入一個結構,但是當我讀取二進制文件時,我發現當它打印出單獨構建它似乎出來正確,但在第四次閱讀它似乎將它添加到最後一次閱讀的最後一名成員。C++讀取二進制數據到結構

這裏的代碼可能使更感比我如何解釋它:

STRUC

#pragma pack(push, r1, 1) 
struct header 
{ 
    char headers[13]; 
    unsigned int number; 
    char date[19]; 
    char fws[16]; 
    char collectversion[12]; 
    unsigned int seiral; 
    char gain[12]; 
    char padding[16]; 

}; 

主要

header head; 
    int index = 0; 
    fstream data; 
    data.open(argv[1], ios::in | ios::binary); 
    if(data.fail()) 
    { 
     cout << "Unable to open the data file!!!" << endl; 
     cout << "It looks Like Someone Has Deleted the file!"<<endl<<endl<<endl; 
     return 0; 

    } 
    //check the size of head 
    cout << "Size:" << endl; 
    cout << sizeof(head) << endl; 
    data.seekg(0,std::ios::beg); 




    data.read((char*)(&head.headers), sizeof(head.headers)); 

    data.read((char*)(&head.number), sizeof(head.number)); 

    data.read((char*)(&head.date), sizeof(head.date)); 

    data.read((char*)head.fws, sizeof(head.fws)); 


//Here im just testing to see if the correct data went in. 
    cout<<head.headers<< endl; 
    cout<<head.number<< endl; 
    cout<<head.date<< endl; 
    cout<<head.fws<< endl; 


    data.close(); 

    return 0; 

輸出

Size: 
96 
CF001 D 01.00 
0 
15/11/2013 12:16:56CF10001001002000 
CF10001001002000 

出於某種原因f ws似乎添加到head.date?但是當我拿出行來閱讀head.fws我得到一個沒有添加任何東西的日期?

我也知道thier更多的數據得到了頭,但我想檢查數據到什麼我寫了是正確的

歡呼

回答

7

您的日期被聲明爲:

char date[19]; 

2.您的日期格式正好是19個字符長:

15/11/2013 12:16:56 

3.,則在打印這樣說:

cout<<head.date 

不久上講,你嘗試使用它的地址,這意味着打印固定char[],它會被解釋爲空值終止 C-字符串。它是否以null結尾?

號爲解決這一問題,宣佈date爲:

char date[20]; 

你填寫後,追加空終止:

date[19] = 0; 

它適用於所有成員,將被解釋爲字符串文字。

+0

我擊敗了你3秒,但你的回答更完整:-)。有一個+1 –

+0

我明白你是對的,但他更好地解釋它歡呼傢伙 – angrymuffins

2

您有char date[19]填充了15/11/2013 12:16:56這正是19個有效字符。這不會留下任何空格來終止空值,因此做cout < < head.date輸出您的19個有效字符,然後輸出垃圾。