Reputation: 69
How to read a binary file with different format of length?
for example there are a specific value after 3200 bytes of binary file which formated in 4 bytes, 2 bytes, 2 bytes, and 1 bytes.
I tried to read using
fread(&buffer, 1, 1, file);
then contenate the 4 bytes char in buffer variable - into one char - then convert it to integer but it doesn't work. Only show like if it was one byte length.
Upvotes: 0
Views: 210
Reputation: 13786
First you seek to the position you want to read:
fseek(file, 3200, SEEK_SET);
Then read the 4 bytes out of the file to the integer you want:
int n;
fread(&n, 4, 1, file);
This works if the endian of the file and your system are the same. Otherwise you convert the number to the endian of you system. E.g.
// if the file is big endian:
m = be32toh(n);
// if the file is little endian:
m = le32toh(n);
Upvotes: 2