MATLAB Answers

Binary file reading.

12 views (last 30 days)
Pappu Murthy
Pappu Murthy on 11 Sep 2018
Commented: Greg on 14 Sep 2018
I have a binary file data which I am trying to read. the first data of record is 8 integer numbers. They are precision "int" which means each number is 4 byte long. so I use A = fread(fid,[1 8],'int') it showas numbers A(2) thru A(8) correctly... but number A(1) is some strange number. Also the last number is missing. If I do A = fread(fid, [1,9],'int') and take the numbers A(2) thru A(9) I am able to read all my numbers correctly. SO my question is why the very first number is some unwanted stuff and needs to be skipped to read correctly.


Sign in to comment.

Accepted Answer

Greg on 11 Sep 2018
Edited: Greg on 11 Sep 2018
Nobody can possibly answer your question: "why... unwanted stuff...?" Only the author of the binary file format can tell you that. --More specifically, those 4 bytes actually exist in the file. MATLAB isn't misbehaving in any way.
I can tell you that you've already solved your problem. Simply skip 4 bytes and proceed. I bet they are useful somehow, but not likely as an int32. Try other 4-byte formats like float32, or 4*char. Maybe it's a float32 datestamp?


Show 6 older comments
Image Analyst
Image Analyst on 12 Sep 2018
You say "I really don't know how it was written." Well, maybe not what program wrote it or the source code of that program, but you must at least know the format because you say "I need to read a lot more stuff involving integers, floating point numbers etc." and it will be impossible to get the right bytes into the right variables unless you know the format. Unless you're purely guessing and that usually only works for the very simplest of formats. So since you know the format and what bytes mean what, you probably should know what the first few bytes mean.
Pappu Murthy
Pappu Murthy on 12 Sep 2018
I agree with you completely. At this point, since I do not have any more info, I am trying to guess and do some reverse engineering. I initially thought if I translated the fortran read statements to matlab read statements I would be able to read the file but now I am finding it is a lot more involved than my simplistic assumption.
Greg on 14 Sep 2018
FYI, frewind is redundant immediately after fopen.
Further, fseek is better than reading and trashing unwanted bytes. For a single value it won't make much difference in speed, but the code is cleaner.
*Accidentally posted as answer. Moved to comment *

Sign in to comment.

More Answers (0)