Files I/O handling in Forth

150 Views Asked by At

While learning Forth I have the following issue, concerning files I/O handling.

I am reading this tutorial https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Files-Tutorial.html and trying to make sense of it. I have been able to deal with almost all of it (including copy-file), but I have a problem with the scan-file word.

I have the following foo.in input file:

$ cat foo.in
Hello world ...
Today is a beautiful day of November.
It is the 8th of November.
The text I search is here.
Actions speak louder than words.
$

I have this code (which runs with no problem) :

0 Value fd-in

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

: open-input ( addr u -- )  r/o open-file throw to fd-in ;

: 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 ;

s" foo.in" open-input

Then I try this, expecting some results (of some kind):

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

I get the following:

s" The text I search is here" scan-file  ok
.s <0>  ok

Even if I change the string "The text I search is here" to some other arbitrary content; I see no difference in the result.

Can someone tell me what is supposed to happen and where I need to look.

At this point: scan-file seems to do nothing.

1

There are 1 best solutions below

8
On BEST ANSWER

It's a problem in your tutorial. Also, the code does not contain anything specific to Gforth.

I would suggest the following variant for learning purposes:

0 value fd-in

256 constant max-line
max-line 2 +  chars  buffer: line-buffer

: open ( addr u -- )  r/o open-file throw to fd-in ;
: close ( -- ) fd-in if fd-in close-file throw 0 to fd-in then ;
: rewind ( -- ) 0 0 fd-in reposition-file throw ;

: scan ( addr u -- flag )
  rewind begin
    line-buffer max-line fd-in read-line throw
  while
    line-buffer swap  2over  search  nip nip
  until
    true
  then
  nip nip
;

s" foo.in" open
s" November" scan .
s" December" scan .
close