views:

21

answers:

2

I've got a char* buffer to hold a file that i read in binary mode. I know the length of the file is 70 bytes and this is the value being used to produce a buffer of the correct size. The problem is, there is 17 or 18 extra spaces in the array so some random characters are being added to the end. Could the be a unicode issue?

ulFLen stores the size of the file in bytes and has the correct value (70 for the file i'm testing on)

//Set up a buffer to store the file
pcfBuffer = new char[ulFLen];

//Reading the file
cout<<"Inputting File...";
fStream.seekg(0,ios::beg);
fStream.read(pcfBuffer,ulFLen);
if(!fStream.good()){cout<<"FAILED"<<endl;}else{cout<<"SUCCESS"<<endl;}
+2  A: 

As it is a char array, you probably forgot a terminating NUL character.

The right way in this case would be:

//Set up a buffer to store the file and a terminating NUL character
pcfBuffer = new char[ulFLen+1];

//Reading the file
cout<<"Inputting File...";
fStream.seekg(0,ios::beg);
fStream.read(pcfBuffer,ulFLen);
if(!fStream.good()){cout<<"FAILED"<<endl;}else{cout<<"SUCCESS"<<endl;}

// Add NUL character
pcfBuffer[ulFLen] = 0;

But note that you only need a terminating NUL character for routines that depend on it, like string routines or when using printf using %s. If you use routines that use the fact that you know the length (70 characters), it will work without a NUL character, too.

schnaader
Thank you, worked perfectly
Dox5
A: 

Add following snippet after the data has been read, it will add the terminating Zero which is needed.

And btw it should be pcfBuffer = new char[ulFLen+1];

size_t read_count = fStream.gcount();
if(read_count<=ulFlen)
    pcfBuffer[read_count]=0;

This will work no matter how much data has to be read (in your case gcount() should always return 70, so you could do following instead: pcfBuffer[70]=0;)

smerlin