开发者

MS Visual c++ 2008 char buffer longer than defined

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 adde开发者_如何转开发d 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;}


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.


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;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜