OK, so the code is not that hard really. We will look at it piece by piece.
1. Create a pointer of type character to hold the file. We will initially set this pointer to NULL.
2. Lets create an integer to hold the determined size of the file:
[COLOR=Bluechar[/COLOR]* myFileBuffer = NULL;
3. Lets open a file:
4. This is where it gets a little confusing for some people. We need to determine the size of the file so we know how much to read. In order to do
this we are going to take advantage of two members of fstream, seekg and tellg.
a. seekg places the current position in the stream. So if we did something like this:
we would move 0 char away from the end of the file. Similarly if we did something like this:
We would move 2 char away from the begginning of the file, aka we would skip the first two characters.
b. tellg() is even simpiler. It returns the current position of the stream pointer. Thus if we did this:
We would recieve the value of 2. (Numbers start at 0).
cout << myFile.tellg();
Alright now with that discussed one can see that to determine the length of a file you would
simply place the stream input at the end of the file and then ask for the number of characters skipped.
5. Now that we know how large the file is, we need to allocate enough memory in our buffer to hold the file. We accomplish this by using new:
myFilesize = myFile.tellg();
6. With the memory allocated now it is time to read the file into our buffer. However remember that
myFileBuffer = new char[myFilesize];
we moved the file pointer to the end of the file, so the first thing we need to do is move it back to the begginning of the file:
7. Now we read the file into our buffer:
8. Like all good strings we need to ensure that they end with '/0'. So we add it to the end of the string:
9. And finally we print out the contents of our file buffer with cout:
myFileBuffer[myFilesize] = '\0';
cout << myFileBuffer << endl;