[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: how to know number of lines from input file
From: |
Jaroslav Hajek |
Subject: |
Re: how to know number of lines from input file |
Date: |
Wed, 7 Oct 2009 11:18:00 +0200 |
On Wed, Oct 7, 2009 at 4:56 AM, febty febriani <address@hidden> wrote:
> Dear all,
>
> If I have command like below :
>
> fh=fopen("$dir/data-1day-1Hz/result-${year}${month}${num}.dat","r");
> y=fscanf(fh,"%lf");
>
> are there any tricks to know number of lines from the input file?
> any helps are appreciated.
> thanks very much.
>
>
> best regards,
> febty
>
> --
>
I have realized that fskipl, which was on my TODO list, could be
slightly extended to be usable also for this purpose, which often
comes up.
-- Built-in Function: fskipl (FID, COUNT)
Skips a given number of lines, i.e. discards characters until an
end-of-line is met exactly COUNT-times, or end-of-file occurs.
Returns the number of lines skipped (end-of-line sequences
encountered). If COUNT is omitted, it defaults to 1. COUNT may
also be `Inf', in which case lines are skipped to the end of file.
This form is suitable for counting lines in a file.
See also: fgetl, fgets
So, with fskipl, you can now easily count lines of a file in advance by
fid = fopen (..., "r");
nlines = fskipl (fid, Inf);
frewind (f);
of course, the file must be seekable (no pipe or socket). Optionally
you may want to add +1 to nlines to account for the characters between
the last newline and EOF (usually there are none, because most editors
and programs consistently terminate each line by \n).
fskipl is now available in development sources:
http://hg.savannah.gnu.org/hgweb/octave/rev/531280b07625
Still, you should be aware that this method requires two walks through the file.
--
RNDr. Jaroslav Hajek
computing expert & GNU Octave developer
Aeronautical Research and Test Institute (VZLU)
Prague, Czech Republic
url: www.highegg.matfyz.cz