I fread() 16 bit binary data perfectly, but doing an fwrite() of that same data into a new file produces problems
3 views (last 30 days)
Show older comments
Jeffrey Sundberg
on 28 Oct 2015
Edited: Walter Roberson
on 29 Oct 2015
I have an input text file opened for reading. It contains a 1024 byte header and then a variable amount of 16 bit binary data. I read it as such:
SynthesizedHeader = fread(InputFId,1024, 'char*1');
[FieldData,DZTBytes] = fread(InputFId,[NumberOfRows, Inf], '*int16', 0, 'ieee-le');
So far, so good. The header is parsable, array dimensions and data types are correct, and the data plots as expected, so all is being read correctly. I make some minor adjustments to the information in the header but don't touch the FieldData at all.
I then want to take the data that I just read and put it into a newly created output file. The code that I've got is this:
OutputFId = fopen( fullfile (OutputPath, OutputFileName),'wt'); % create a new output file
fwrite ( OutputFId, SynthesizedHeader, 'char*1');
fwrite ( OutputFId, FldData, 'int16', 0, 'ieee-le');
Here is the problem: while the first fwrite() results in a perfect header in the output file, there are too many data items written by the second fwrite(). (For example, I properly fread in 884736 bytes into the FieldData because it is a 512 x 864 array of int16s; but I fwrite out 894290 bytes as demonstrated by both ftell() and the size of the output file on disk.)
This problem happens even if I comment out the first fwrite() or reshape the data matrix to be one dimensional- clearly I'm doing something wrong with the format of the second fwrite(), but cannot determine what that may be.
Many thanks in advance for identifying my mistake!
0 Comments
Accepted Answer
Walter Roberson
on 29 Oct 2015
When you use fwrite() you should avoid opening the file with 't' access. 't' requests translation of linefeed to carriage-return + linefeed pairs. Use 'w' in the fopen not 'wt'
1 Comment
More Answers (0)
See Also
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!