2013-07-11 172 views
2

我想讀這個二進制文件並在屏幕上打印數字,但它打印奇怪的字符。我從MATLAB生成這個二進制文件。我如何正確顯示數據?閱讀二進制文件

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

ifstream::pos_type size; 
char * memblock; 

int main() 
{ 
    ifstream file ("seg.bin", ios::in|ios::binary|ios::ate); 

    if (file.is_open()) 
    { 
     size = (int)file.tellg(); 
     memblock = new char [size]; 
     file.seekg (0, ios::beg); 
     file.read (memblock, size); 
     file.close(); 

     cout << "the complete file content is in memory"; 

     for (int i=0;i<size;i++) 
     { 
      cout<<memblock[i]<<endl; 
     } 
    } 
    else cout << "Unable to open file"; 
    return 0; 
} 
+0

這樣做:'cout <<(int)memblock [i] << endl;' – sgarizvi

+1

@ sgar91如果原始數據的類型爲「char」,那麼只會這樣做。 OP沒有告訴我們數據類型是什麼。 – paddy

+0

請記得刪除後面的[] memblock,以防止內存泄漏 – Enigma

回答

0

你需要知道文件中存儲的數據類型是什麼。假設它是double。在這種情況下,你可以這樣做:

for (int i = 0; i < size; i += sizeof(double)) 
{ 
    cout << *(double*)&memblock[i] << endl; 
} 

另一種方式去了解它是直接讀入的double數組開始。將這個作爲一個練習。

1

要打印char s到輸出,在輸出char的表示是一個字符,如果你發送到std::cout的字未見諸報端,你會看到什麼或在某些情況下,你會看到奇怪的字符(或者在某些情況下會發出嗶嗶聲!)。

嘗試投的charint

std::cout << static_cast<int>(memblock[i]) << std::endl; 
      ^^^^^^^^^^^^^^^^ 

你迭代印刷時的數據,你會只得到8位大小的數據的方式(或者你char是大小),讓我們supose你有你的文件中的以下數據:

00000FFF 

你的輸出將是:

但是,如果你有其他尺寸(int爲例)的數據時,你會想到的4095輸出(或0如果你的數據是16位寬的,則爲4095)。

如果是你的情況下,嘗試將數據讀入數據的數組你期待:

const ifstream::pos_type size = file.tellg(); // do not cast the size! 
const size_t elements = size/sizeof(int); // <--- beware of the sizes! 
memblock = new int [elements];    // Elements, not size 

for (int i = 0; i < elements; ++i) // Elements! not size 
{ 
    std::cout << memblock[i] << std::endl; 
} 

另一個提示:

  • 聲明sizeelements爲const(你」閱讀後不會改變它們):這向您和您的同事表明您打算將這些變量視爲只讀。
  • 請勿將size轉換爲int,請使用tellg()的返回類型或使用autoconst auto size = file.tellg();:爲什麼要轉換爲另一種類型?使用您所調用的功能的相同功能!演員陣容可能會導致開銷。
  • 嘗試在最小範圍內以及將要使用它們的位置附近聲明變量:這將使您的代碼更具可讀性和可維護性。
0

memblock是char類型,這就是爲什麼cout將使字符打印(ascii字符)。 在這種情況下,您想要將memblock指針reinterpret_cast重新指向所需類型的指針。 說你需要加倍:

size = (int)file.tellg(); 
memblock = new char [size]; 
file.seekg (0, ios::beg); 
file.read (memblock, size); 
file.close(); 
double * fileContent = reinterpret_cast<double *>(memblock); 
cout << "the complete file content is in memory"; 

int sizeOfFileContent = sizeof(memblock)/sizeof(double); 
for (int i=0; i<sizeOfFileContent; i++) 
{ 
    cout<<fileContent[i]<<endl; 
} 

僅使用一個指針來回收內存,不要試圖多次刪除它!