Reading a binary file

From Bitpost wiki
Revision as of 15:12, 18 May 2006 by M (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

  // EXAMPLES
  /*
  #include <iostream>
  #include <fstream>
  using namespace std;
  int main(void)
  {
     const unsigned int Matrix_Rows = 256;
     const unsigned int Matrix_Cols = 256;
     unsigned char area_matrix[Matrix_Rows * Matrix_Cols];
     unsigned char pointers_matrix[Matrix_Rows][Matrix_Cols];
     ifstream data_file("filename", ios::binary);
     // Reading an area of bytes 
     data_file.read(area_matrix, sizeof(area_matrix));
     // Rewinding the input file 
     data_file.clear(); // just in case.
     data_file.seekg(0);
     // Reading a two-dimensional array of bytes 
     for (unsigned int i = 0; i < Matrix_Rows; ++i)
     {
     data_file.read(pointers_matrix[i],
                    Matrix_Cols);
     }
     return 0;
  } 
  #include &ltfstream>
  #include &ltctime>
  #include &ltstring>
  #include &ltvector>
  using namespace std;
  int main()
  {
  std::ifstream in("pp1.txt",std::ios::binary);
  if (!in)
  {
     std::cout << "problem with file open" << std::endl;
     return 0;
  }
  clock_t c1,c2;
  c1 = clock();
  in.seekg(0,std::ios::end);
  unsigned long length = in.tellg();
  in.seekg(0,std::ios::beg);
     vector< char > vTmp(length+1,0);
     in.read(&vTmp[0],length);
     string str;
     str.reserve(length);
     str.assign(&vTmp[0],&vTmp[0]+length); // no NULL at end
    
  c2 = clock();
  std::cout << static_cast< double >(c2-c1)/static_cast< double >(CLOCKS_PER_SEC) << std::endl;
  return 0;
  }
  directly into std::string
  #include &ltiostream>
  #include &ltfstream>
  #include &ltctime>
  #include &ltstring>
  using namespace std;
  int main()
  {
  std::ifstream in("pp1.txt",std::ios::binary);
  if (!in)
  {
  std::cout << "problem with file open" << std::endl;
  return 0;
  }
  clock_t c1,c2;
  c1 = clock();
  in.seekg(0,std::ios::end);
  unsigned long length = in.tellg();
  in.seekg(0,std::ios::beg);
  string str(length,0);
  std::copy( std::istreambuf_iterator< char >(in) ,
  std::istreambuf_iterator< char >() ,
  str.begin() );


  c2 = clock();
  std::cout << static_cast< double >(c2-c1)/static_cast< double >(CLOCKS_PER_SEC) << std::endl;
  return 0;
  }
  */