fread

Reads the binary data of the precision type from the file fileID.

Syntax

[values , count] = fread(fileID, size, precision, skip)

Inputs

fileID
FileID returned from previous call to fopen().
Type: double | integer
size
Amount of data to read. If omitted, inf assumed.
Type: double | integer
Valid entries for size:
  • inf - indicates to read as much data as possible, returning a column vector.
  • number - read indicated number of data points, returning a column vector.
  • [num_rows, inf ] - read as much data as possible, returning a matrix with num_rows.
  • [num_rows, num_cols] - read num_rows * num_cols data points, returing a matrix with num_rows.
precision
String specifying the type of data to read. See fwrite for all available types.
Type: string
skip
Number of bytes to skip.
Type: double | integer

Outputs

values
Matrix of values read from the file. The matrix dimensions will depend on the size argument and the amount of data in the file.
Type: matrix
count
The number of values read from the file.
Type: double | integer

Example

Read example using fwrite and fread functions:
% open file using 'w+'
fileID = fopen('testfile', 'w+')
% create a matrix
M = [ 1923.71288  4023.03575  9768.82832  9195.83701  104.13143  4261.35201   ];
% write matrix to file
fwrite_result = fwrite(fileID, M, 'double')
fflush_result = fflush(fileID)
printf('\n')
% return as much as possible in a column vector
frewind_result = frewind(fileID);
R1 = fread(fileID, inf, 'double');
printf('Matrix dimensions: columns %2d  rows %2d\n', size(R1)(2), size(R1)(1));

% return 2 values in a column vector
frewind_result = frewind(fileID);
R2 = fread(fileID, 2, 'double');
printf('Matrix dimensions: columns %2d  rows %2d\n', size(R2)(2), size(R2)(1));

% return as much as possible in 2 rows
frewind_result = frewind(fileID);
R3 = fread(fileID, [2, inf], 'double');
printf('Matrix dimensions: columns %2d  rows %2d\n', size(R3)(2), size(R3)(1));

% return 2 entries in 1 row
frewind_result = frewind(fileID);
R4 = fread(fileID, [1, 2], 'double');
printf('Matrix dimensions: columns %2d  rows %2d\n', size(R4)(2), size(R4)(1));

fclose_result = fclose(fileID)
fileID = 5
fwrite_result = 6
fflush_result = 0
 
Matrix dimensions: columns  1  rows  6
Matrix dimensions: columns  1  rows  2
Matrix dimensions: columns  3  rows  2
Matrix dimensions: columns  2  rows  1
fclose_result = 0