www.delorie.com/gnu/docs/gforth/gforth_41.html   search  
 
Buy GNU books!


Gforth Manual

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.26.3 Scan file for a particular line

 
256 Constant max-line
Create line-buffer  max-line 2 + allot

: scan-file ( addr u -- )
  begin
      line-buffer max-line fd-in read-line throw
  while
         >r 2dup line-buffer r> compare 0=
     until
  else
     drop
  then
  2drop ;

read-line ( addr u1 fd -- u2 flag ior ) reads up to u1 bytes into the buffer at addr, and returns the number of bytes read, a flag that's true when the end of file is reached, and an error code.

compare ( addr1 u1 addr2 u2 -- n ) compares two strings and returns zero if both strings are equal. It returns a positive number if the first string is lexically greater, a negative if the second string is lexically greater.

We haven't seen this loop here; it has two exits. Since the while exits with the number of bytes read on the stack, we have to clean up that separately; that's after the else.

Usage example:

 
s" The text I search is here" scan-file


  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003