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!