--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
1. Allocate a big contiguous area in memory, large enough
to contain the contents of the file.
For example:
const unsigned int MAX_SIZE = 10 * 1024 * 1024;
unsigned char * p_big_file(0);
p_big_file = new unsigned char [MAX_SIZE];
if (!p_big_file)
{
// memory allocation failure,
// process it here.
}
2. Use istream.read to input the file:
ifstream the_data_file("filename", ios::binary);
// It may need to be ios_base::binary
the_data_file.read(p_big_file, MAX_SIZE);
I'll leave obtaining the number of bytes read as
an exercise for the OP.
Some notes:
1. Many platforms cannot allocate huge amounts of memory
as local variables (a.k.a. stack variables), or even
as global variables.
2. Many platforms have more dynamic memory space than
the other types. This is commonly known as the heap.
3. Your platform, compiler, or OS may have functions to
treat files as memory. Look it up.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library
Correct me if I'm wrong: new unsigned char [MAX_SIZE] will throw
std::bad_alloc if it fails to allocate memory, and it will never
return 0.
The code should therefore look like this:
try {
const unsigned int MAX_SIZE = 10 * 1024 * 1024;
unsigned char * p_big_file = new unsigned char [MAX_SIZE];
// do somthing with p_bif_file
}
catch ( std::bad_alloc& )
{
// memory allocation failure,
// process it here.
}
Regards
--
If you don't know the size of the file beforehand, you can determine
the length at runtime and allocate an array that fits the file
exactly.
The following example was taken from:
http://cplusplus.com/reference/iostream/istream/seekg/
// load a file into memory
#include <iostream>
#include <fstream>
using namespace std;
int main () {
int length;
char * buffer;
ifstream is;
is.open ("test.txt", ios::binary );
// get length of file:
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// allocate memory:
buffer = new char [length];
// read data as a block:
is.read (buffer,length);
is.close();
cout.write (buffer,length);
delete[] buffer;
return 0;
Unless you use VC6 or specifically tell the compiler not to. (Maybe
because you have used VC6 and don't want the code to break in VC8.)
br,
Martin