B Seven
B Seven

Reputation: 45941

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

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

fskipl undefined.

Upvotes: 0

Views: 3902

Answers (1)

mtrw
mtrw

Reputation: 35098

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.

Upvotes: 2

Related Questions