How to read just a part of a binary file with a predefined end position or a predefined amount of Bytes?
23 views (last 30 days)
Show older comments
Hi. I have searched a lot to find the answer, but was not successful.
I want to get data records ({'uint16' 'uint16' 'uint16' 'uint8' 'uint8'} = 8 Bytes) out of a binary file.
The files have millions of records with 1 min time steps and a given start date.
Up to now, I was able to define the start position by skipping the wanted time duration (1 record of 8 Bytes = 1 min) with fseek.
My problem is, that I can not find a solution how to define the end position or the amount of records for fread.
One solution would be to use a Loop in which the record length is added to fseek each run and the rest of the file is skipped after every record. But this is grossly inefficient and likely would need even more time than reading the whole file and picking the wanted part out of the resulting matrix, I guess.
I hope you understand what I want to ask...
I need something like fread(fileID,start_position,end_position or number of records).
Thanks in advance.
3 Comments
Image Analyst
on 12 Dec 2018
I deal with 3-D CT images of up to 20 GB in size and I use fseek() and fread() to read slices out of the middle of the file and it's pretty quick, like a second or two. I'm not aware of any other ways, so you might call the Mathworks and ask them. How big are your files?
Accepted Answer
Guillaume
on 12 Dec 2018
I'm not entirely sure I completely understand, maybe that's what you want:
recordstart = ??? %some integer value. Index of first desired record
numrecords = ??? %how many records to get
filepath = ??? %path of the file
recordtypes = {'uint16', 'uint16', 'uint16', 'uint8', 'uint8'};
recordsizes = [2, 2, 2, 1, 1]; %size of each type in bytes. Must match recordtypes
fid = fopen(filepath, 'r')
fseek(fid, (recorstart - 1) * sum(recordsizes), 'bof');
data = fread(fid, [sum(recordsizes), numrecords], '*uint8'); %read numrecords as uint8
data = mat2cell(data, recordsizes, numrecords);
data = cellfun(@(bytes, data) typecast(bytes(:), data), data', recordtypes, 'UniformOutput', false);
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!