I have a text file, containing an array of numbers such as:
1 0 0 1 0
0 1 1 0 1
0 0 0 1 1
1 1 0 0 0
0 0 1 0 0
I have opened the text file with the following code:
variable file-id
: open_file ( -- ) \ Opens the text file
s" c:\etc\textfile.txt" r/w open-file throw
file-id ! ;
I have also created an array to store this data:
create an_array 25 chars allot \ Create the array
: reset_array ( -- ) big_array 25 0 fill ;
reset_array \ Set all elements to 0
Is there a way to write the contents of the text file into the array with Forth?
1. Lazy way
A lazy way is to just evaluate a file by performing
included
on the file name.2. Tidy way
A careful way is to read a file (completely, or line by line), split the text into lexemes, convert lexemes into numbers, then store the numbers into your array.
See: How to enter numbers in Forth .
On a low level it can be done via
read-file
orread-line
, something likeword|tail
and>number
(or something likeStoN
library word from the example above).On a higher level: use Gforth specific words like
execute-parsing
orexecute-parsing-file
,parse-name
ands>number?
If you need to read too many numbers, you have to write them into the array one by one at once, instead of placing all of them into the stack.