fread, longs and cheap PCs
Hi,
I've been trying to load a file into memory, using the following code:-
Code:
long fsize(FILE *fp)
{
long pos, size;
pos = ftell(fp);
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, pos, SEEK_SET);
return size;
}
int main(void)
{
unsigned char *temp;
long filesize;
FILE *fp;
fp = fopen("data.dat", "rb");
filesize = fsize(fp);
temp = (unsigned char *)malloc(filesize);
if (temp == NULL)
{
printf("Memory allocation error\n");
return -1;
}
fread(temp, filesize, 1, fp);
return 0;
}
However, when I compile this with Borland Turbo C 2.0, using a large memory model and then run it, it crashes (and on these cheap Cyrix MX/S3 Virge-based PCs my school uses, the screen messes up completely...).
It seems that temp is allocated correctly (malloc doesn't return NULL), but the fread statement is causing bother. The fact that I'm using a long for filesize when size_t is defined as an unsigned int (max 65,535) is concerning, but as the file I'm testing it on is only 48,200 bytes, it shouldn't overflow upon truncation, should it?
Re: fread, longs and cheap PCs
There might be other problems . . . like some error checking that isn't being done, etc., but one thing that you'll need to do is change:
fread(temp, filesize, 1, fp);
to
fread(temp, (size_t)filesize, (size_t)1, fp);
Hope This Helps,
Joshua Burkholder