Line count in macro read_file()

Tony Balinski ajbj at free.fr
Tue Apr 8 20:05:44 CEST 2008


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



More information about the Discuss mailing list