ifstream::read and NULL's

Feb 14, 2010 at 10:25pm
I have the following code that reads the contents of a file:
1
2
3
4
5
6
7
8
9
10
11
12
ifstream iFile(pFilename);
iFile.seekg(0, ios::end);
int length = iFile.tellg();
iFile.seekg(0, ios::beg);

char *pFileBuffer = new char[length + 1];
iFile.read(pFileBuffer);

// Do some stuff.

iFile.close();
delete [] pFileBuffer;


The code works great for the most part but I have problems when the file contains any NULL's other than the one that must be at the end of the file. Is there someway to get around this using the ifstream class? If not is there another standard class that I could use that does not have this problem?

Thanks!
~Dudester~
Feb 14, 2010 at 10:30pm
I don't believe there is an STL replacement for the fstream hierarchy. (Check boost, boost has everything)
I'm not sure what the eof character is but seekg might be looking for that, not a null... I don't have the experience with that whole readpoint manipulation to say. Just a guess.
Last edited on Feb 14, 2010 at 10:30pm
Feb 14, 2010 at 10:50pm
7
8
iFile.read(pFileBuffer, length);
pFileBuffer[length] = '\0';

Hope this helps.
Feb 14, 2010 at 10:53pm
Oops lol I wrote the code in the post wrong. I do have that. As far as I can tell the problem is the seekg method. It stops at any null it finds even if that null is not near the end of the file.
Feb 15, 2010 at 1:40am
Well I found out a way around the problem using only the standard library but I have a feeling that the code is going to run pretty slow on any file of significant length (aka more than 1kb).

1
2
3
4
5
6
7
8
ifstream iFile(pFilename);
string sFileBuffer;
while(!iFile.eof())
     sFileBuffer.push_back(iFile.get());

// Do some stuff.

iFile.close();
Feb 15, 2010 at 2:36am
I just noticed that you did not open the file in binary mode.
1
2
ifstream iFile(pFilename, ios::binary);
...

The seek and tell functions don't account for newline translation on windows.

Hope this helps.
Topic archived. No new replies allowed.