23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Using Low-Level File I/O Functions<br />

function y = litcount(filename, literal)<br />

% Search for number of string matches per line.<br />

fid = fopen(filename, 'rt');<br />

y = 0;<br />

while feof(fid) == 0<br />

tline = fgetl(fid);<br />

matches = findstr(tline, literal);<br />

num = length(matches);<br />

if num > 0<br />

y = y + num;<br />

fprintf(1,'%d:%s\n',num,tline);<br />

end<br />

end<br />

fclose(fid);<br />

For example, consider the following input data file called badpoem:<br />

Oranges and lemons,<br />

Pineapples and tea.<br />

Orangutans and monkeys,<br />

Dragonflys or fleas.<br />

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

litcount('badpoem','an')<br />

2: Oranges and lemons,<br />

1: Pineapples and tea.<br />

3: Orangutans and monkeys,<br />

Reading Formatted ASCII Data<br />

The fscanf function is like the fscanf function in standard C. Both functions<br />

operate in a similar manner, reading data from a file and assigning it to one<br />

or more variables. Both functions use the same set of conversion specifiers to<br />

control the interpretation of the input data.<br />

The conversion specifiers for fscanf begin with a % character; common<br />

conversion specifiers include.<br />

6-111

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!