MS Visual c++ 2008 字符缓冲区比定义的长
我有一个 char* 缓冲区来保存我以二进制模式读取的文件。我知道文件的长度是 70 字节,这是用于生成正确大小的缓冲区的值。问题是,数组中有 17 或 18 个额外空格,因此一些随机字符被添加到末尾。可能是 unicode 问题吗?
ulFLen 以字节为单位存储文件的大小并具有正确的值(我正在测试的文件为 70)
//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;}
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;}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于它是一个
char
数组,您可能忘记了终止 NUL 字符。在这种情况下,正确的方法是:
但请注意,对于依赖于它的例程,您只需要一个终止 NUL 字符,例如字符串例程或使用
%s
使用printf
时。如果您使用的例程使用了已知长度(70 个字符)的事实,那么它也可以在没有 NUL 字符的情况下工作。As it is a
char
array, you probably forgot a terminating NUL character.The right way in this case would be:
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.读取数据后添加以下代码片段,它将添加所需的终止零。
顺便说一句,它应该是
pcfBuffer = new char[ulFLen+1];
无论需要读取多少数据(在您的情况下
gcount()
应该始终返回 70,因此您可以执行以下操作:pcfBuffer[70]=0;
)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];
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;
)