fread
Reads binary data from a file.
Category: Data Import and Analysis > Data Import and Export
Syntax
A = fread(fid)
Reads the rest of the file as unsigned bytes into a column of doubles.
A = fread(fid, sizeA, precision)
Reads sizeA values of the given type.
A = fread(fid, sizeA, precision, skip, machinefmt)
Skips bytes between values and sets the byte order.
[A, count] = fread(...)
Also returns the number of values read.
Description
Reading starts at the current file position and moves it forward, so successive calls walk through the file. Open the file in binary mode for non-text data. To read a text file as characters in one call, fread(fid, Inf, '*char')' returns the whole content.
Input arguments
sizeAnfor a column of up tonvalues,Inffor all, or[m n]to fill anm-by-nmatrix column by column.precision- Type in the file, such as
'uint8','int16','single','double','char'. Write'uint8=>char'to also convert the output, or'*char'as a shorthand for the same type in and out. machinefmt- Byte order:
'l'little-endian,'b'big-endian.
Output arguments
A- Data read. The class is double unless the precision uses
=>or*. count- Number of values read.
Example
Mixed binary record
fid = fopen('f.bin', 'w');
fwrite(fid, 'ABC');
fwrite(fid, pi, 'double');
fwrite(fid, [1 2], 'int16', 'b');
fclose(fid);
fid = fopen('f.bin');
txt = fread(fid, 3, '*char')'
x = fread(fid, 1, 'double')
v = fread(fid, 2, 'int16', 0, 'b')'
fclose(fid);
Output
txt = 'ABC'
x = 3.1416
v = 1×2
1 2