Documentation Center

  • Trial Software
  • Product Updates
我们为许可用户提供了部分翻译好的中文文档。您只需登录便可查阅这些文档

fscanf

Read data from text file

Syntax

  • A = fscanf(fileID,formatSpec) example
  • A = fscanf(fileID,formatSpec,sizeA) example
  • [A,count] = fscanf(___) example

Description

example

A = fscanf(fileID,formatSpec) reads data from an open text file into column vector A and interprets values in the file according to the format specified by formatSpec. The fscanf function reapplies the format throughout the entire file and positions the file pointer at the end-of-file marker. If fscanf cannot match formatSpec to the 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 character encoding, and obtain the fileID value. When you finish reading, close the file by calling fclose(fileID).

example

A = fscanf(fileID,formatSpec,sizeA) reads file data into an array, A, with dimensions, sizeA, and positions the file pointer after the last value read. fscanf populates A in column order.

example

[A,count] = fscanf(___) additionally returns the number of fields that fscanf reads into A. For numeric data, this is the number of values read. You can use this syntax with any of the input arguments of the previous syntaxes.

Examples

expand all

Read File Contents into Column Vector

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.4724
90.5792
12.6987
91.3376
63.2359
9.7540
27.8498
54.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 the string, '%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 =

   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

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.8147
2 0.9058
3 0.1270
4 0.9134
5 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)
fclose(fileID);
A =

    1.0000    2.0000    3.0000    4.0000    5.0000
    0.8147    0.9058    0.1270    0.9134    0.6324

Transpose the array so that A matches the orientation of the data in the file.

A = A'
A =

    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
    49


count =

     5

A is a vector containing the numeric values in the file. count indicates that fscanf read five values.

Input Arguments

expand all

fileID — File identifierinteger

File identifier of an open text file, specified as an integer. Before reading a file with fscanf, you must use fopen to open the file and obtain the fileID.

Data Types: double

formatSpec — Format of data fieldsstring

Format of the data fields in the file, specified as a string of one or more conversion specifiers. When fscanf reads a file, it attempts to match the data to the formatSpec string.

Numeric Fields

This table lists available conversion specifiers for numeric inputs. fscanf converts values to their decimal (base 10) representation.

Numeric Field TypeConversion SpecifierDetails

Integer, signed

%d

Base 10

%i

The values in the file determine the base:

  • The default is base 10.

  • If the initial digits are 0x or 0X, then the values are hexadecimal (base 16).

  • If the initial digit is 0, then values are octal (base 8).

%ld or %li

64-bit values, base 10, 8, or 16

Integer, unsigned

%u

Base 10

%o

Base 8 (octal)

%x

Base 16 (hexadecimal)

%lu, %lo, %lx

64-bit values, base 10, 8, or 16

Floating-point number

%f

Floating-point fields can contain any of the following (not case sensitive): Inf, -Inf, NaN, or -NaN.

%e

%g

Character Fields

This table lists available conversion specifiers for character inputs.

Character Field TypeConversion SpecifierDescription

Characters

%s

Read a string until fscanf encounters white space.

%c

Read any single character, including white space.
To read multiple characters at a time, specify field width.

Pattern-matching string

%[...]

Read only characters in the brackets up to the first nonmatching character or white space.

Example: %[mus] reads 'summer ' as 'summ'.

If formatSpec contains a combination of numeric and character specifiers, then fscanf converts each character to its numeric equivalent. This conversion occurs even when 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 characters in your file in sequence, unless you tell it to ignore a particular field 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 to read at a time, insert a number after the percent character. For example, %10c reads up to 10 characters at a time, including white space. %4f reads up to 4 digits at a time, including the decimal point.

  • Literal Text to Ignore

    fscanf ignores specified text appended to the formatSpec string.

    Example: Level%u reads 'Level1' as 1.

    Example: %uStep reads '2Step' as 2.

sizeA — Dimensions of output arrayInf (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 InputDescription
InfRead to the end of the file.
For numeric data, the output, A, is a column vector.
For text data, A is a string.
nRead at most n numeric values or character fields.
For numeric data, the output, A, is a column vector.
For text data, A, is a string.
[m,n]Read at most m*n numeric values or character fields. n can be Inf, but m cannot. The output, A, is m-by-n, filled in column order.

Output Arguments

expand all

A — File datacolumn vector | matrix | string | character array

File data, returned as a column vector, matrix, string, or character array. The class and size of A depend on the formatSpec input:

  • If formatSpec contains only numeric specifiers, then A is numeric. If you specify the sizeA argument, then A is a matrix of the specified size. Otherwise, A is a column vector. If the input contains fewer than sizeA values, then fscanf pads A with zeros.

    • If formatSpec contains only 64-bit signed integer specifiers, then A is of class int64.

    • If formatSpec contains only 64-bit unsigned integer specifiers, then A is of class uint64.

    • Otherwise, A is of class double.

  • If formatSpec contains only character or string specifiers (%c or %s), then A is a character array. If you specify sizeA and the input contains fewer characters, then fscanf pads A with char(0).

  • If formatSpec contains a combination of numeric and character specifiers, then A is numeric, of class double, and fscanf converts each text characters to its numeric equivalent. This occurs even when formatSpec explicitly skips all numeric fields (for example, formatSpec is '%*d %s').

  • If MATLAB® cannot match the file data to formatSpec, then A can be numeric or a character array. The class of A depends on the values that fscanf reads before it stops processing.

count — Number of characters readscalar

Number of characters read, returned as a scalar value.

More About

expand all

Tips

  • Format specifiers for the reading functions sscanf and fscanf differ from the formats for the writing functions sprintf and fprintf. The reading functions do not support a precision field. The width field specifies a minimum for writing but a maximum for reading.

Algorithms

MATLAB reads characters using the encoding scheme associated with the file. You specify the encoding when you open the file using the fopen function.

See Also

| | | | | |

Was this topic helpful?