Reading a binary file
// 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 <fstream>
#include <ctime>
#include <string>
#include <vector>
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 <iostream>
#include <fstream>
#include <ctime>
#include <string>
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;
}
*/