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.
Code:
[COLOR=Bluechar[/COLOR]* myFileBuffer = NULL;
2. Lets create an integer to hold the determined size of the file:
3. Lets open a file:
Code:
myFile.open("myFile.txt", ios_base::in);
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:
Code:
myFile.seekg(0, ios_base::end);
we would move 0 char away from the end of the file. Similarly if we did something like this:
Code:
myFile.seekg(2, ios_base::beg);
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:
Code:
myFile.seekg(2, ios_base::beg);
cout << myFile.tellg();
We would recieve the value of 2. (Numbers start at 0).
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.
Code:
myFile.seekg(0, ios_base::end);
myFilesize = myFile.tellg();
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:
Code:
myFileBuffer = new char[myFilesize];
6. With the memory allocated now it is time to read the file into our buffer. However remember that
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:
Code:
myFile.seekg(0, ios_base::beg);
7. Now we read the file into our buffer:
Code:
myFile.read(myFileBuffer, myFilesize);
8. Like all good strings we need to ensure that they end with '/0'. So we add it to the end of the string:
Code:
myFileBuffer[myFilesize] = '\0';
9. And finally we print out the contents of our file buffer with cout:
Code:
cout << myFileBuffer << endl;