如何解决在Forth上将文本文件写入数组 1懒惰方式 2整洁的方式
我有一个文本文件,其中包含数字数组,例如:
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
我用以下代码打开了文本文件:
variable file-id
: open_file ( -- ) \ Opens the text file
s" c:\etc\textfile.txt" r/w open-file throw
file-id ! ;
我还创建了一个数组来存储此数据:
create an_array 25 chars allot \ Create the array
: reset_array ( -- ) big_array 25 0 fill ;
reset_array \ Set all elements to 0
是否可以使用Forth将文本文件的内容写入数组?
解决方法
1。懒惰方式
一种懒惰的方法是通过对文件名执行included
来评估文件。
\ Some library-level common words
\ --------------------------------
\ Store n chars from the stack into the array at c-addr,n >= 0
: c!n ( n*x n c-addr -- )
>r begin dup while ( i*x i )
\ store top from i*x into addr+(i-1)*char_size
1- tuck chars r@ + c! ( j*x j )
repeat drop rdrop
;
\ Execute xt and produce changing in the stack depth
: execute-balance ( i*x xt -- j*x n ) depth 1- >r execute depth r> - ;
: included-balance ( i*x c-addr u -- j*x n )
['] included execute-balance 2 +
;
\ The program
\ --------------------------------
create myarray 25 chars allot \ Create the array
: read-myfile-numbers ( -- i*x i )
state @ abort" Error: only for interpretation"
s" ./mynumbers.txt" included-balance
;
: write-myarray ( i*x i -- )
dup 25 <> abort" Error: exactly 25 numbers are expected"
myarray c!n
;
: fill-myarray-from-myfile ( -- )
read-myfile-numbers write-myarray
;
2。整洁的方式
一种谨慎的方法是 读取文件(完全或逐行),将文本拆分为词素,将词素转换为数字,然后将数字存储到数组中。
请参阅:How to enter numbers in Forth 。
在较低级别上,可以通过read-file
或read-line
完成,例如word|tail
和>number
(或类似StoN
上面的示例)。
在更高的层次上:使用Gforth专用词,例如execute-parsing
或execute-parsing-file
,parse-name
和s>number?
: next-lexeme ( -- c-addr u|0 )
begin parse-name ?dup if exit then ( addr )
refill 0= if 0 exit then drop
again
;
: read-myfile-numbers ( -- i*x i )
s" ./mynumbers.txt" r/o open-file throw
[:
0 begin next-lexeme dup while
s>number? 0= abort" Error: NaN" d>s swap 1+
repeat 2drop
;] execute-parsing-file
;
如果需要读取太多的数字,则必须一次将它们一次写入数组,而不是将它们全部放入堆栈中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。