Programming Previous page   Next Page

Reading Strings Line by Line from Text Files

MATLAB provides two functions, fgetl and fgets, that read lines from formatted text files and store them in string vectors. The two functions are almost identical; the only difference is that fgets copies the newline character to the string vector but fgetl does not.

The following M-file function demonstrates a possible use of fgetl. This function uses fgetl to read an entire file one line at a time. For each line, the function determines whether an input literal string (literal) appears in the line.

If it does, the function prints the entire line preceded by the number of times the literal string appears on the line.

For example, consider the following input data file called badpoem:

To find out how many times the string 'an' appears in this file, use litcount:


Previous page  Controlling Position in a File Reading Formatted ASCII Data Next page

© 1994-2005 The MathWorks, Inc.