The most efficient but not C ++ way:
FILE* f = fopen(filename, "r"); // Determine file size fseek(f, 0, SEEK_END); size_t size = ftell(f); char* where = new char[size]; rewind(f); fread(where, sizeof(char), size, f); delete[] where;
# EDIT - 2
Just tested the std::filebuf . It seems that it can be called the best C ++ approach, although this is not quite an approach in C ++, but rather a shell. Anyway, here is a piece of code that runs almost as fast as regular C.
std::ifstream file(filename, std::ios::binary); std::streambuf* raw_buffer = file.rdbuf(); char* block = new char[size]; raw_buffer->sgetn(block, size); delete[] block;
I did a quick test here and the results follow. The test was conducted while reading the 65536K binary with the corresponding modes ( std::ios:binary and rb ).
[==========] Running 3 tests from 1 test case. [----------] Global test environment set-up. [----------] 4 tests from IO [ RUN ] IO.C_Kotti [ OK ] IO.C_Kotti (78 ms) [ RUN ] IO.CPP_Nikko [ OK ] IO.CPP_Nikko (106 ms) [ RUN ] IO.CPP_Beckmann [ OK ] IO.CPP_Beckmann (1891 ms) [ RUN ] IO.CPP_Neil [ OK ] IO.CPP_Neil (234 ms) [----------] 4 tests from IO (2309 ms total) [----------] Global test environment tear-down [==========] 4 tests from 1 test case ran. (2309 ms total) [ PASSED ] 4 tests.
Costantino Rupert May 26 '10 at 11:46 a.m. 2010-05-26 11:46
source share