matlab函数fgetl和fgets:按行读取格式文本函数
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);
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,