如何计算Octave中文本文​​件中的行数?

时间:2011-12-16 21:18:43

标签: octave

并且不要说fskipl因为它不起作用!

fskipl undefined

1 个答案:

答案 0 :(得分:2)

你有fgetl吗?如果是这样,你可以做这个小循环:

f = fopen('myfile.txt', 'rt');
ctr = 0;
ll = fgetl(f);
while (!isnumeric(ll)) %# fgetl returns -1 when it hits eof. But you can't do ll != -1 because blank lines make it barf
    ctr = ctr+1;
    ll = fgetl(f);
end
fclose(f);

否则,你可以做一些黑客攻击:

f = fopen('myfile.txt', 'rb');
ctr = 0;
[x, bytes] = fread(f, 8192); %# use an 8k intermediate buffer, change this value as desired
while (bytes > 0)
    ctr = ctr + sum(x == 10); %# 10 is '\n'
    [x, bytes] = fread(f, 8192);
end
fclose(f);

10是换行符的ASCII码。但这似乎是不可靠的,特别是如果你遇到一个使用回车而不是换行的文件。