您好,我正在尝试使用方案命令从二进制文件中找到第40个字节。
(define FileName "D:/work_dsi/Stories/WriterOptions/Tests/block_english.model")
(define fPtr (open-input-file FileName))
(define sRec "1")
(((sRec (read-byte fPtr)))
do
((eof-object? sRec ))
(print sRec)
(define sRec (read-byte fPtr))
)
(close-input-port fPtr)
我试着用这个表达式来更好地理解这个概念,但是什么也没得到。
您需要这些功能:
- with-input-from-file:允许您从给定的文件(文件被设置为当前输入端口)读取
- port->bytes:从给定端口或当前输入端口获取所有字节,结果为字节字符串
- bytes-ref:从字节串中获取第n个字节
(require racket/port)
(with-input-from-file
"D:/work_dsi/Stories/WriterOptions/Tests/block_english.model"
(lambda ()
(bytes-ref (port->bytes) 39)))
这个函数将返回number。对于读取文本文件,您可以将该数字转换为整数->char以获得character.
仅使用标准R7RS函数的版本(特别是file
库中的open-binary-input-file
和read-u8
:
(import (scheme file))
(define (read-nth-byte filename n)
(call-with-port
(open-binary-input-file filename)
(lambda (inp)
(do ((i 1 (+ i 1))
(byte (read-u8 inp) (read-u8 inp)))
((= i n) byte)
(if (eof-object? byte) (error "Premature end of file"))))))
为了避免在n
值较大的情况下将文件的大块读取到内存中,这个文件读取并丢弃字节,直到它到达n
字节为止。(如果标准中有seek
函数就好了…)