I fread() 16 bit binary data perfectly, but doing an fwrite() of that same data into a new file produces problems
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2015-10-29
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'
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Low-Level File I/O 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!