fread
Read data from binary file
Syntax
Description
reads data from an open binary file into column vector A
= fread(fileID
)A
and
positions the file pointer at the end-of-file marker. The binary file is indicated
by the file identifier, fileID
. Use fopen
to
open the file and obtain the fileID
value. When you finish
reading, close the file by calling fclose(fileID)
.
additionally specifies the order for reading bytes or bits in the file.A
= fread(___,machinefmt
)
Examples
Read Entire File of uint8 Data
Write a nine-element vector to a sample file, nine.bin
.
fileID = fopen('nine.bin','w'); fwrite(fileID,[1:9]); fclose(fileID);
Read all the data in the file into a vector of class double
. By default, fread
reads a file 1 byte at a time, interprets each byte as an 8-bit unsigned integer (uint8
), and returns a double
array.
fileID = fopen('nine.bin');
A = fread(fileID)
A = 9×1
1
2
3
4
5
6
7
8
9
fread
returns a column vector, with one element for each byte in the file.
View information about A
.
whos A
Name Size Bytes Class Attributes A 9x1 72 double
Close the file.
fclose(fileID);
Read Entire File of Double-Precision Data
Create a file named doubledata.bin
, containing nine double-precision values.
fileID = fopen('doubledata.bin','w'); fwrite(fileID,magic(3),'double'); fclose(fileID);
Open the file, doubledata.bin
, and read the data in the file into a 3-by-3 array, A
. Specify that the source data is class double
.
fileID = fopen('doubledata.bin'); A = fread(fileID,[3 3],'double')
A = 3×3
8 1 6
3 5 7
4 9 2
Close the file.
fclose(fileID);
Read Selected Rows or Columns from File
Create a file named nine.bin
, containing the values from 1 to 9. Write the data as uint16
values.
fileID = fopen('nine.bin','w'); fwrite(fileID,[1:9],'uint16'); fclose(fileID);
Read the first six values into a 3-by-2 array. Specify that the source data is class uint16
.
fileID = fopen('nine.bin'); A = fread(fileID,[3,2],'uint16')
A = 3×2
1 4
2 5
3 6
fread
returns an array populated column-wise with the first six values from the file, nine.bin
.
Return to the beginning of the file.
frewind(fileID)
Read two values at a time, and skip one value before reading the next values. Specify this format using the precision
value, '2*uint16'
. Because the data is class uint16
, one value is represented by 2 bytes. Therefore, specify the skip
argument as 2
.
precision = '2*uint16';
skip = 2;
B = fread(fileID,[2,3],precision,skip)
B = 2×3
1 4 7
2 5 8
fread
returns a 2-by-3 array populated column-wise with the values from nine.bin
.
Close the file.
fclose(fileID);
Read Digits of Binary Coded Decimal Values
Create a file with binary coded decimal (BCD) values.
str = ['AB'; 'CD'; 'EF'; 'FA']; fileID = fopen('bcd.bin','w'); fwrite(fileID,hex2dec(str),'ubit8'); fclose(fileID);
Read 1 byte at a time.
fileID = fopen('bcd.bin'); onebyte = fread(fileID,4,'*ubit8');
Display the BCD values.
disp(dec2hex(onebyte))
AB CD EF FA
Return to the beginning of the file using frewind
. If you read 4 bits at a time on a little-endian system, your results appear in the wrong order.
frewind(fileID)
err = fread(fileID,8,'*ubit4');
disp(dec2hex(err))
B A D C F E A F
Return to the beginning of the file using frewind
. Read the data 4 bits at a time as before, but specify a big-endian ordering to display the correct results.
frewind(fileID) correct = fread(fileID,8,'*ubit4','ieee-be'); disp(dec2hex(correct))
A B C D E F F A
Close the file.
fclose(fileID);
Input Arguments
fileID
— File identifier
integer
File identifier of an open binary file, specified as an integer. Before
reading a file with fread
, you must use fopen
to open the file and
obtain its identifier fileID
.
Data Types: double
sizeA
— Dimensions of output array
Inf
(default) | integer | two-element row vector
Dimensions of the output array, A
, specified as
Inf
, an integer, or a two-element row
vector.
Form of the sizeA
Input | Dimensions of the output array,
A |
---|---|
Inf | Column vector, with each element containing a value in the file. |
| Column vector with n elements.
|
| m -by-n matrix,
filled in column order. n can be
Inf , but m
cannot. |
precision
— Class and size of values to read
'uint8=>double'
(default) | character vector or string scalar
Class and size in bits of the values to read, specified as a character
vector or a string scalar in one of the following forms. Optionally the
input specifies the class of the output matrix, A
.
Form of the precision
Input | Description |
---|---|
source | Input values are of the class specified by
source . Output matrix
A is class double .
Example: 'int16' |
source =>output | Input values are of the class specified by
source . The class of the
output matrix, A , is specified by
output .
Example: 'int8=>char' |
* | The input values and the output matrix,
A , are of the class specified by
source . For
bit
or ubit
precisions, the output has the smallest class that can
contain the input.Example: '*ubit18'
This is equivalent to 'ubit18=>uint32' |
| Read |
The following table shows possible values for
source
and
output
.
Value Type | Precision | Bits (Bytes) |
---|---|---|
Integers, unsigned |
|
|
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
Integers, signed |
|
|
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
Floating-point numbers |
|
|
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
Characters |
|
|
| The MATLAB® |
For most values of source
, if
fread
reaches the end of the file before reading a
complete value, it does not return a result for the final value. However, if
source
is
bit
or
n
ubit
, then
n
fread
returns a partial result for the final
value.
Note
To preserve NaN
and Inf
values
in MATLAB, read and write data of class double
or
single
.
Data Types: char
| string
skip
— Number of bytes to skip
0 (default) | scalar
Number of bytes to skip after reading each value, specified as a scalar.
If you specify a precision
of
bit
or
n
ubit
, specify
n
skip
in bits.
Use the skip
argument to read data from noncontiguous
fields in fixed-length records.
machinefmt
— Order for reading bytes
'n'
(default) | 'b'
| 'l'
| 's'
| 'a'
| ...
Order for reading bytes in the file, specified as a character vector or a
string scalar. Specify machinefmt
as one of the values in
the table that follows. For
bit
and
n
ubit
precisions,
n
machinefmt
specifies the order for reading bits
within a byte, but the order for reading bytes remains your system byte
ordering.
| Your system byte ordering (default) |
| Big-endian ordering |
| Little-endian ordering |
| Big-endian ordering, 64-bit long data type |
| Little-endian ordering, 64-bit long data type |
By default, all currently supported platforms use little-endian ordering for new files. Existing binary files can use either big-endian or little-endian ordering.
Data Types: char
| string
Output Arguments
A
— File data
column vector | matrix
File data, returned as a column vector. If you specified the
sizeA
argument, then A
is a matrix
of the specified size. Data in A
is class
double
unless you specify a different class in the
precision
argument.
count
— Number of characters read
scalar
Number of characters read, returned as a scalar value.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
The input argument
precision
must be a constant.The
source
andoutput
classes thatprecision
specifies cannot have these values:'long'
,'ulong'
,'unsigned long'
,'bit
, orn
''ubit
.n
'You cannot use the
machinefmt
input.If the
source
oroutput
thatprecision
specifies is a C type, for example,int
, then the target and production sizes for that type must:Match.
Map directly to a MATLAB type.
The
source
type thatprecision
specifies must map directly to a C type on the target hardware.If the
fread
call reads the entire file, then all of the data must fit in the largest array available for code generation.If
sizeA
is not constant or contains a nonfinite element, then dynamic memory allocation is required.The code generator for the
fread
function treats thechar
value forsource
oroutput
as a signed8
-bit integer. Use values between0
and127
only.The generated code does not report file read errors. Therefore, you must write your own file read error handling in your MATLAB code. In your error handling code, consider checking that the number of bytes read matches the number of bytes that you requested. For example:
... N = 100; [vals, numRead] = fread(fid, N, '*double'); if numRead ~= N % fewer elements read than expected end ...
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Version History
Introduced before R2006aR2024b: Read data over HTTP and HTTPS using low-level file functions
You can read data from primary online sources by performing low-level file read operations over an internet URL.
R2022b: Use function in thread-based environments
This function supports thread-based environments.
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)