arrays - 在 Forth 上将文本文件写入数组
问题描述
我有一个文本文件,其中包含一个数字数组,例如:
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.整洁的方式
一种谨慎的方法是读取文件(完整或逐行),将文本拆分为词位,将词位转换为数字,然后将数字存储到数组中。
请参阅:如何在 Forth 中输入数字。
在低级别上,它可以通过read-file
or来完成read-line
,类似于word|tail
and >number
(或类似于StoN
上面示例中的库词)。
在更高的层次上:使用 Gforth 特定的词,如execute-parsing
or 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
;
如果需要读取的数字太多,就必须一次一个地将它们写入数组,而不是全部放入堆栈。
推荐阅读
- excel - 访问事件中的名称时发生 VBA 错误 1004
- flutter - 使用 Json 错误是 * type 'List
' 不是 'String' 类型的子类型* - android - 数据绑定生成的类内存不是很重吗?
- python - 使用 nodejs 的 Python 签名许可证验证
- c# - 导出到“C:/temp/”后,bitbucket 管道在哪里存储文件
- php - 如何解决 PHPSpread sheet not found 错误
- google-chrome-devtools - 如何使用 chrome devtools 协议进行调试
- laravel - 公用文件夹问题中的 Cron 脚本
- ios - 接口生成器中的未知类 + NSUnknownKeyException
- swift - 为什么我无法在 init 中获取我的 fetchedResults?