user3897338
user3897338

Reputation:

Reading from binary after x bytes in C

I am trying to read double values from a binary in C, but the binary starts with an integer and then the doubles I am looking for. How do I skip that first 4 bytes when reading with fread()? Thanks

Upvotes: 1

Views: 2483

Answers (4)

pah
pah

Reputation: 4778

Be careful when implementing things like this. If the file isn't created on the same machine, you may get invalid values due to different floating point specifications.

If the file you're reading is created on the same machine, make sure that the program that writes, correctly address the type sizes.

If both writer and reader are developed in C and are supposed to run only on the same machine, use the fseek() with the sizeof(type) used in the writer in the offset parameter.

If the machine that writes the binary isn't the same that will read it, you probably don't want to even read the doubles with fread() as their format may differ due to possible different architectures.

Many architectures rely on the IEEE 754 for floating point format, but if the application is supposed to address multi-platform support, you should make sure that the serialized format can be read from all architectures (or converted while unserializing).

Upvotes: 1

JuniorCompressor
JuniorCompressor

Reputation: 20025

Try this:

fseek(input, sizeof(int), SEEK_SET);

before any calls to fread.

As Weather Vane said you can use sizeof(int) safely if the file was generated in the same system architecture as the program you are writing. Otherwise, you should manually specify the size of integer of the system where the file originated.

Upvotes: 4

Igor Popov
Igor Popov

Reputation: 2620

You can use fseek to skip the initial integer. If you insist on using fread anyway, then you can read the integer first:

fread(ptr, sizeof(int), 1, stream).

Of course you have to declare ptr before calling fread.

As I said, fseek is another option:

fseek(stream, sizeof(int), SEEK_SET).

Beware that fseek moves the file pointer in bytes (1 in the given line from the beginning of the file); integer can be 4 or other number of bytes which is system specific.

Upvotes: 1

alexcleac
alexcleac

Reputation: 29

Just read those 4 unneeded bytes, like

void* buffer = malloc(sizeof(double));
fread(buffer,4,1,input); //to skip those four bytes

fread(buffer,sizeof(double),1,input); //then read first double =)
double* data = (double*)buffer;//then convert it to double 

And so on

Upvotes: -1

Related Questions