Reputation: 4585
The size of the test.bin is 7,01,760 bytes. I am trying to read date from this file as "short" in a buffer bufferPointer.
short * bufferPointer=NULL;
// ==> ANSWER WAS ADDING: bufferPointer = ( short*)malloc(350880); <==
FILE *fp=fopen(" test.bin","rb");
fread(bufferPointer,sizeof(short),350880 ,fp);
fclose(fp);
I am getting Debug Assertion Failed at fread(). Why?
MSVC2010, Windows-7-32 bit
Upvotes: 0
Views: 2650
Reputation: 14039
Try this
short bufferPointer[350880];
FILE *fp=fopen("test.bin","rb");
fread(bufferPointer,sizeof(short),350880 ,fp);
fclose(fp);
Few things here
1) You cannot use a pointer directly in this way. Either statically allocate memory like above or use malloc to allocate dynamically
2) There is a space in the beginning in the string " test.bin". Remove the leading space.
3) Even if the above works, it may not give you meaningful results. fread
reads stuff which has been written by fwrite
. i.e. was the file creating using fwrite
writing short
s? If not, what you read may make no sense.
Upvotes: 1
Reputation: 1564
sgar91 is correct. Just try:
short * bufferPointer = (short *)malloc(350880*sizeof(short));
if (bufferPointer == NULL)
{
// TODO: error handling
}
FILE *fp = fopen("test.bin", "rb");
if (fp == NULL)
{
// TODO: error handling
}
fread(bufferPointer, sizeof(short), 350880, fp);
fclose(fp);
Upvotes: 1
Reputation: 16406
You allocated 350880 bytes for your buffer but tried to read 350880 shorts. Try
bufferPointer = malloc(350880 * sizeof *bufferPointer);
(Note that casting malloc isn't necessary, and is frowned upon because it can hide bugs.)
You should also check your malloc, fopen, and fread calls for errors.
Upvotes: 6
Reputation: 16796
You should first allocate sufficient amount of memory to the bufferPointer
by using malloc
. Then you can use fread
to read from the file into that buffer.
Upvotes: 3