Read variable length binary files into memory???

I'm teaching myself C, for Cocoa later on, so _please_ forgive my C newbie factor of 10. :)

I need to read variable lengths of the rest of a binary files (typically 80k-150k), from a variable offset in the file, and can't figure out how to do this.

In my admittedly lacking mind, here's how it should work:

i = fread(&fnsz, 4, 1, fp);
fnsz = NSSwapInt(fnsz);

const void *act_file;

act_file = malloc(fnsz);

i = fread(&act_file, fnsz, 1, fp);

Thanks in advance, for any help, more C tutorials, directions, etc.
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

KocilConnect With a Mentor Commented:
Yes, you have an excelent mind.
Only a little bit correction

i = fread(&fnsz, 4, 1, fp);
fnsz = NSSwapInt(fnsz); // I assume this return the length of the rest

const char *act_file;  // use char*, not void*
act_file = malloc(fnsz);

i = fread(act_file, fnsz, 1, fp); // don't use & on act_file
// it is already a pointer

// process the act_file, then dont forget to free it


This code will work on Windows or Linux, but not on DOS because DOS can malloc no more than 64K memory.


Kent OlsenData Warehouse Architect / DBACommented:

Close.  Just a couple of minor things to keep you moving.

'act_file' is not a 'const'.  It's a pointer that you're going to change by placing in it the address returned by malloc().  The buffer that it will point to will also be changed when you do the read ().

The address passed to fread() is 'act_file', not '*act_file'.  'act_file' contains the address of the buffer and that's what you need to pass to fread ();

Good Luck

CocoaNewbOnOSXAuthor Commented:
Thank you both for your help, you people rock.

Kocil: NSSwapInt is an Apple macro that converts from little endian to big endian.

Here's the code at this moment. After reading it, I coerce it into an NSData object for the rest of my needs. Thanks you both, again.

... //parse to relevant int

i = fread(&fnsz, 4, 1, fp); //then read it
fnsz = NSSwapInt(fnsz); //swap vyte order (comes from PC sys)

char *act_file; //NOT a constant!!! ;-)

act_file = malloc(fnsz); //alloc w/ NO pointers, thanks for tip!

i = fread(act_file, fnsz, 1, fp); //read and create data object from it...

NSData *tempData = [NSData dataWithBytes:act_file length:fnsz];

CocoaNewbOnOSXAuthor Commented:
Kocil: I must admit, I didn't understand how this site worked. So, you should have definetly gotten more than 5 points and also an A!! Sorry about that. :-)
All Courses

From novice to tech pro — start learning today.