Line count in macro read_file()

YT Lim ytlim23 at yahoo.com.au
Wed Apr 9 16:41:22 CEST 2008


Thanks Tony & Alexey,

Since Alexey's method fits better with my macro, as such I only need his for loop for the job. So I've chosen Alexey's. BTW, I only deal with small files.

Regards,
/Y.T.

----- Original Message ----
From: Tony Balinski <ajbj at free.fr>
To: General NEdit discussion list <discuss at nedit.org>
Sent: Tuesday, 8 April, 2008 8:05:44 PM
Subject: Re: Line count in macro read_file()

Quoting AVKuznetsov <kuzn at htsc.mephi.ru>:

> On Tue, 8 Apr 2008 01:36:49 -0700 (PDT)
> YT Lim <ytlim23 at yahoo.com.au> wrote:
>
> > Is there a way to know how many lines of text have been read by the macro
> subroutine read_file()?
> >
> > /Y.T.
> >
>
> Hi,
> you can try the following macro
>
> define read_file_line_count{
>     string = read_file($1) # File name is an argument.
>     if(!$read_status)
>         return -1      # Reading error.
>     if(string == "")
>         return 0       # Empty file.
>     for(i=1, start=0; search_string(string, "\n", start) >= 0; i++)
>         start = $search_end
>     return i           # Number of lines.
> }
Alternatively,
  s = read_file(filename)
  nls = replace_in_string(s, ".*", "", "regex")
  return length(nls) + (s != "" && substring(s, -1) != "\n")

In other words, nls is a copy of s where all characters other than "\n"
have been removed. So it contains only as many "\n"s as the original.
The last bit, substring(s, -1) != "\n", just says "add 1 if the last line
isn't terminated with a "\n".

You could also do
  a = split(read_file(filename), "\n")
  n = a[]
  n -= (n > 0 && a[n - 1] == "") # no partial last line?
  return n
if you don't mind setting up an array holding all the lines of your file.

These two methods probably run faster than Alexey's since the main effort
is performed by compiled C rather than interpreted. However, both are more
expensive in terms of memory, needing at least twice the file's size.

Tony

-- 
NEdit Discuss mailing list - Discuss at nedit.org
http://www.nedit.org/mailman/listinfo/discuss





      Get the name you always wanted with the new y7mail email address.
www.yahoo7.com.au/y7mail




More information about the Discuss mailing list