2016-08-25 154 views
1

我嘗試通過下面的C++程序讀取二進制數據。但它不能顯示值。 The data保存爲8位無符號字符。讓我知道如何解決它。通過C++讀取二進制數據

#include <iostream> 
#include <fstream> 
using namespace std; 

int main(int argc,char *argv[]) 
{ 
    if(argc!=2) 
    { 
     cout << "argument error" << endl; 
     return 1; 
    } 

    ifstream file (argv[1], ios::in|ios::binary); 
    //ifstream fin(outfile, ios::in | ios::binary); 

    if (!file) 
    { 
     cout << "Can not open file"; 
     return 1; 
    } 

    unsigned char d; 

    while(!file.eof()) 
    { 
     file.read((char *) &d, sizeof(unsigned char)); 

     cout << d << endl; 
    } 

    file.close(); 

    return 0; 
} 

回答

6

首先是don't do while (!file.eof())

然後爲您的問題:這是你輸出一個字符。這意味着數據流將嘗試將其打印爲字符,這對二進制數據來說是不正確的。

如果您想打印您讀取的值,則需要將其轉換爲整數。像

std::cout << std::hex << std::setw(2) << std::setfill('0') << 
      << static_cast<unsigned int>(d); 

上面應該打印出的值爲2位十六進制數字。重要的是static_cast

+0

正如您所說,該值可以由固定程序顯示0和1。我想在8位顯示0和255。讓我知道如何去做。 – LenItsuki

+0

@LenItsuki我不確定你的意思是...你的意思是說,輸入文件中的每個*字節只能是單個'1'或'0'?你可以編輯你的問題,包括輸入文件的部分十六進制轉儲(不,沒有人會下載並打開一個未知文件,如你鏈接到的)。 –

+0

我弄錯了文件中包含的值。 0和1都OK!感謝您的建議。 – LenItsuki