| Development Environment | ![]() |
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.
function y = litcount(filename, literal) % Search for number of string matches per line. fid = fopen(filename, 'rt'); y = 0; while feof(fid) == 0 tline = fgetl(fid); matches = findstr(tline, literal); num = length(matches); if num > 0 y = y + num; fprintf(1,'%d:%s\n',num,tline); end end fclose(fid);
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.
| Controlling Position in a File | Reading Formatted ASCII Data | ![]() |