Programming Previous page   Next Page

Reading Formatted ASCII Data

The fscanf function is like the fscanf function in standard C. Both functions operate in a similar manner, reading data from a file and assigning it to one or more variables. Both functions use the same set of conversion specifiers to control the interpretation of the input data.

The conversion specifiers for fscanf begin with a % character; common conversion specifiers include

Conversion Specifier
Description
%s
Match a string.
%d
Match an integer in base 10 format.
%g
Match a double-precision floating-point value.

You can also specify that fscanf skip a value by specifying an asterisk in a conversion specifier. For example, %*f means skip the floating-point value in the input data; %*d means skip the integer value in the input data.

Differences Between the MATLAB fscanf and the C fscanf

Despite all the similarities between the MATLAB and C versions of fscanf, there are some significant differences. For example, consider a file named moon.dat for which the contents are as follows:

The following code reads all three elements of this file into a matrix named MyData:

Notice that this code does not use any loops. Instead, the fscanf function continues to read in text as long as the input format is compatible with the format specifier.

An optional size argument controls the number of matrix elements read. For example, if fid refers to an open file containing strings of integers, then this line reads 100 integer values into the column vector A:

This line reads 100 integer values into the 10-by-10 matrix A:

A related function, sscanf, takes its input from a string instead of a file. For example, this line returns a column vector containing 2 and its square root:


Previous page  Reading Strings Line by Line from Text Files Writing Formatted Text Files Next page

© 1994-2005 The MathWorks, Inc.