[英]To many char read by fread
Im am trying to open a file in binary mode and write the content to a buffer in C++.我正在尝试以二进制模式打开文件并将内容写入 C++ 中的缓冲区。 I am using
fread
for this.我正在为此使用
fread
。 However something goes wrong.然而,出了点问题。 My code is:
我的代码是:
FILE * in = fopen("in", "rb");
_in = new unsigned char [length_in];
fread(_in, sizeof(char), length_in, in);
When debugging i can see that _in = unsigned char * "Asdfghjkl\\x1f \\x10"
.调试时我可以看到
_in = unsigned char * "Asdfghjkl\\x1f \\x10"
。
When rebuilding the program, the part \\x1f \\x10
changes randomly or disappears.重建程序时,
\\x1f \\x10
部分随机变化或消失。
What i am expecting is always _in = unsigned char * "Asdfghjkl"
.我期待的总是
_in = unsigned char * "Asdfghjkl"
。
When replacing length_in
with 9
i still get something like "Asdfghjkl\\x1f \\x10"
.当用
9
替换length_in
,我仍然得到类似"Asdfghjkl\\x1f \\x10"
。
What am I missing.我错过了什么。 I am using a Mac and Xcode.
我正在使用 Mac 和 Xcode。
Your array is created uninitialized, so those are garbage values from whatever was in memory beforehand.您的数组是在未初始化的情况下创建的,因此这些是来自内存中任何内容的垃圾值。 Initialize it to zeros like this:
将其初始化为零,如下所示:
_in = new unsigned char [length_in]();
Also fread
returns the number of bytes read. fread
还返回读取的字节数。 If you're treating it like a string, make sure the result is null-terminated.如果您将其视为字符串,请确保结果以空字符结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.