按行读取格式文本函数
fprintf格式Matlab提供了两个函数fgetl和fgets来从格式文本文件读取行,并存储到字符串向量中。这两个函数集几乎相同;不同之处是,fgets拷贝新行字符到字符向量,而fgetl则不。
下面的M-file函数说明了fgetl的一个可能用法。此函数使用fgetl一次读取一整行。对每一行,函数判断此行是否包含给定的文字。
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);
badpoem文件如下
Oranges and lemons,
Pineapples and tea.
Orangutans and monkeys,
Dragonflys or fleas.


运行实例:
litcount('badpoem','an')
2: Oranges and lemons,
1: Pineapples and tea.
3: Orangutans and monkeys,

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。