Read data from text file
collapse all in page
Syntax
A = fscanf(fileID,formatSpec)
A = fscanf(fileID,formatSpec,sizeA)
[A,count]= fscanf(___)
Description
example
A = fscanf(fileID,formatSpec)
readsdata from an open text file into column vector A
andinterprets values in the file according to the format specified by formatSpec
.The fscanf
function reapplies the format throughoutthe entire file and positions the file pointer at the end-of-filemarker. If fscanf
cannot match formatSpec
tothe data, it reads only the portion that matches and stops processing.
The text file is indicated by the file identifier, fileID
.Use fopen
to open the file, specify the characterencoding, and obtain the fileID
value. When youfinish reading, close the file by calling fclose(fileID)
.
example
A = fscanf(fileID,formatSpec,sizeA)
readsfile data into an array, A
, with dimensions, sizeA
,and positions the file pointer after the last value read. fscanf
populates A
incolumn order. sizeA
must be a positive integeror have the form [m n]
, where m
and n
arepositive integers.
example
[A,count]= fscanf(___)
additionally returns the numberof fields that fscanf
reads into A
.For numeric data, this is the number of values read. You can use thissyntax with any of the input arguments of the previous syntaxes.
Examples
collapse all
Read File Contents into Column Vector
Open Live Script
Create a sample text file that contains floating-point numbers.
x = 100*rand(8,1);fileID = fopen('nums1.txt','w');fprintf(fileID,'%4.4f\n',x);fclose(fileID);
View the contents of the file.
type nums1.txt
81.472490.579212.698791.337663.23599.754027.849854.6882
Open the file for reading, and obtain the file identifier, fileID
.
fileID = fopen('nums1.txt','r');
Define the format of the data to read. Use '%f'
to specify floating-point numbers.
formatSpec = '%f';
Read the file data, filling output array, A
, in column order. fscanf
reapplies the format, formatSpec
, throughout the file.
A = fscanf(fileID,formatSpec)
A = 8×1 81.4724 90.5792 12.6987 91.3376 63.2359 9.7540 27.8498 54.6882
A
is a column vector containing data from the file.
Close the file.
fclose(fileID);
Read File Contents into Array
Open Live Script
Create a sample text file that contains integers and floating-point numbers.
x = 1:1:5;y = [x;rand(1,5)];fileID = fopen('nums2.txt','w');fprintf(fileID,'%d %4.4f\n',y);fclose(fileID);
View the contents of the file.
type nums2.txt
1 0.81472 0.90583 0.12704 0.91345 0.6324
Open the file for reading, and obtain the file identifier, fileID
.
fileID = fopen('nums2.txt','r');
Define the format of the data to read and the shape of the output array.
formatSpec = '%d %f';sizeA = [2 Inf];
Read the file data, filling output array, A
, in column order. fscanf
reuses the format, formatSpec
, throughout the file.
A = fscanf(fileID,formatSpec,sizeA)
A = 2×5 1.0000 2.0000 3.0000 4.0000 5.0000 0.8147 0.9058 0.1270 0.9134 0.6324
fclose(fileID);
Transpose the array so that A
matches the orientation of the data in the file.
A = A'
A = 5×2 1.0000 0.8147 2.0000 0.9058 3.0000 0.1270 4.0000 0.9134 5.0000 0.6324
Skip Specific Characters in File
Skip specific characters in a sample file,and return only numeric data.
Create a sample text file containing temperature values.
str = '78°C 72°C 64°C 66°C 49°C';fileID = fopen('temperature.dat','w');fprintf(fileID,'%s',str);fclose(fileID);
Read the numbers in the file, skipping the text, °C.Also return the number of values that fscanf
reads.The extended ASCII code 176 represents the degree sign.
fileID = fopen('temperature.dat','r');degrees = char(176);[A,count] = fscanf(fileID, ['%d' degrees 'C'])fclose(fileID);
A = 78 72 64 66 49count = 5
A
is a vector containing the numeric valuesin the file. count
indicates that fscanf
readfive values.
Input Arguments
collapse all
fileID
— File identifier
integer
File identifier of an open text file, specified as an integer.Before reading a file with fscanf
, you must use fopen
toopen the file and obtain the fileID
.
Data Types: double
formatSpec
— Format of data fields
character vector | string scalar
Format of the data fields in the file, specified as a charactervector or string scalar of one or more conversion specifiers. When fscanf
readsa file, it attempts to match the data to the format specified by formatSpec
.
Numeric Fields
This table lists available conversion specifiers for numericinputs. fscanf
converts values to their decimal(base 10) representation.
Numeric Field Type | Conversion Specifier | Details |
---|---|---|
Integer, signed |
| Base 10 |
| The values in the file determine the base:
| |
| 64-bit values, base 10, 8, or 16 | |
Integer, unsigned |
| Base 10 |
| Base 8 (octal) | |
| Base 16 (hexadecimal) | |
| 64-bit values, base 10, 8, or 16 | |
Floating-point number | | Floating-point fields can containany of the following (not case sensitive): |
| ||
|
Character Fields
This table lists available conversion specifiers for characterinputs.
Character Field Type | Conversion Specifier | Description |
---|---|---|
Character vector or string scalar |
| Read all characters excluding white spaces. |
| Read any single character, including white space. | |
Pattern-matching |
| Read only characters in the brackets up to the firstnonmatching character or white space. Example: |
If formatSpec
contains a combination of numericand character specifiers, then fscanf
convertseach character to its numeric equivalent. This conversion occurs evenwhen the format explicitly skips all numeric values (for example, formatSpec
is '%*d%s'
).
Optional Operators
Fields and Characters to Ignore
fscanf
reads all numeric values and charactersin your file in sequence, unless you tell it to ignore a particularfield or a portion of a field. To skip fields, insert an asterisk (*
) after the percent sign (%
).For example, to skip integers, specify%*d
.Field Width
To specify the maximum number of digits or text characters toread at a time, insert a number after the percent character. For example,
%10c
readsup to 10 characters at a time, including white space.%4f
readsup to 4 digits at a time, including the decimal point.Literal Text to Ignore
fscanf
ignores specified text appended totheformatSpec
conversion specifier.Example:
Level%u
reads'Level1'
as1
.Example:
%uStep
reads'2Step'
as2
.
sizeA
— Dimensions of output array
Inf
(default) | integer | two-element row vector
Dimensions of the output array, A
, specifiedas Inf
, an integer, or a two-element row vector.
Form of the sizeA Input | Description |
---|---|
Inf | Read to the end of the file. For numeric data,the output, A , is a column vector. Fortext data, A is a character vector. |
| Read at most n numeric values orcharacter fields. For numeric data, the output, A ,is a column vector.For text data, A ,is a character vector. |
[ | Read at most numericvalues or character fields. n can be Inf ,but m cannot. The output, A ,is m -by-n , filled in columnorder. |
Output Arguments
collapse all
A
— File data
column vector | matrix | character vector | character array
File data, returned as a column vector, matrix, character vectoror character array. The class and size of A
dependon the formatSpec
input:
If
formatSpec
contains only numericspecifiers, thenA
is numeric. If you specify thesizeA
argument,thenA
is a matrix of the specified size. Otherwise,A
isa column vector. If the input contains fewer thansizeA
values,thenfscanf
padsA
with zeros.If
formatSpec
contains only 64-bitsigned integer specifiers, thenA
is of classint64
.If
formatSpec
contains only 64-bitunsigned integer specifiers, thenA
is of classuint64
.Otherwise,
A
is of classdouble
.
If
formatSpec
contains only characteror text specifiers (%c
or%s
),thenA
is a character array. If you specifysizeA
andthe input contains fewer characters, thenfscanf
padsA
withchar(0)
.If
formatSpec
contains a combinationof numeric and character specifiers, thenA
isnumeric, of classdouble
, andfscanf
convertseach text characters to its numeric equivalent. This occurs even whenformatSpec
explicitlyskips all numeric fields (for example,formatSpec
is'%*d%s'
).If MATLAB® cannot match the file data to
formatSpec
,thenA
can be numeric or a character array. Theclass ofA
depends on the values thatfscanf
readsbefore it stops processing.
count
— Number of characters read
scalar
Number of characters read, returned as a scalar value.
Tips
Format specifiers for the reading functions
sscanf
andfscanf
differfrom the formats for the writing functionssprintf
andfprintf
.The reading functions do not support a precision field. The widthfield specifies a minimum for writing but a maximum for reading.
Algorithms
MATLAB reads characters using the encoding scheme associatedwith the file. You specify the encoding when you open the file usingthe fopen
function.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
For MEX code generation, the code generator treats
fscanf
as an extrinsic function. See Use MATLAB Engine to Execute a Function Call in Generated Codein MATLAB Function BlocksDuring Fixed-Point Algorithm Acceleration (MATLAB Coder).The input argument
formatSpec
must be a constant.The
%s
and%[...]
conversion specifiers are not supported.If you turn off dynamic memory allocation, you must provide the input argument
sizeA
and it must be a constant.In certain cases, the behavior of the generated code might differ from MATLAB. In such cases, the behavior of the generated code matches that of
fscanf
in the C language. These are some examples:In the generated code, if
fscanf
reads a null byte, the returned values might be truncated.If you read an integer value
x
into an integer format for whichintmax
is smaller thanx
, the MATLAB output saturates atintmax
. In the generated code, this situation causes an overflow.In certain cases, after
fscanf
reads from a file, the location of the file pointer might be different in MATLAB and the generated code. For example, suppose that the filemyFile.txt
contains the character vector'1+2I'
. You execute these commands:fid = fopen('myFile.txt','r');tmp = fscanf(fid, '%f')
tmp = 1 2
Use ftell to determine the current location of the position pointer in the file
myFile.txt
.ftell(fid)
ans = 3
In MATLAB, after
fscanf
executes, the file pointer is positioned after the third character'2'
. In the generated code, afterfscanf
executes, the file pointer is positioned at the end-of-file marker.
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 R2006a
expand all
R2022b: Use function in thread-based environments
This function supports thread-based environments.
See Also
fopen | fprintf | textscan | sscanf | fgetl | fgets | fread
Topics
- Import Text Data Files with Low-Level I/O
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:
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
- Deutsch
- English
- Français
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本 (日本語)
- 한국 (한국어)
Contact your local office