c++ - reading Binary files -


i want read binary file , print numbers on screen printing weird characters. generated binary file matlab. how can display data properly?

#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 in memory";          (int i=0;i<size;i++)         {             cout<<memblock[i]<<endl;         }     }     else cout << "unable open file";     return 0; } 

you're printing chars output, representation of char in output character, , if character you're sending std::cout isn't printable you'll see nothing or in cases you'll see weird characters (or in cases beep sound!).

try cast char value int:

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

the way you're iterating-printing data you'll data of 8bits size (or size char is), let's supose have following data on file:

00000fff 

your output be:

0

0

15

255

but if you're working data of other sizes (int example) expect output of 4095 (or 0 , 4095 if data 16bits wide).

if case, try read data array of data you're expecting:

const ifstream::pos_type size = file.tellg(); // not cast size! const size_t elements = size / sizeof(int);   // <--- beware of sizes! memblock = new int [elements];                // elements, not size  (int = 0; < elements; ++i) // elements! not size {     std::cout << memblock[i] << std::endl; } 

another tips:

  • declare size , elements const (you're not going change them after reading): shows , workmates intention treat variables read-only.
  • do not cast size int, use type of return of tellg() or use auto: const auto size = file.tellg();: why cast type? use same of function you're calling! casts may lead overhead.
  • try declare variables in tiniest scope , near place you're going use them: make code more readable , maintainable.

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -