How to count the number of lines in a text file in Octave?

可紊 提交于 2019-12-12 04:47:51

问题


And don't say fskipl because it doesn't work!!!

fskipl undefined.


回答1:


Do you have fgetl? If so, you can do this little loop:

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);

Otherwise, you could do some hack like:

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 is the ASCII code for the newline character. But this seems unreliable, especially if you come across a file that uses carriage return instead of newline.



来源:https://stackoverflow.com/questions/8540271/how-to-count-the-number-of-lines-in-a-text-file-in-octave

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!