Sim*_*ine 5 functional-programming ml sml
有没有办法,使用SML Basis库,在特定位置打开文件?也就是说,使用操作系统调用来更改位置,而不是扫描文件并丢弃数据.
这很棘手.不幸的是,寻求不是直接支持的.此外,文件位置仅对二进制文件是透明的,即用BinIO结构[1] 打开的文件.对于这种结构,相应的类型BinIO.StreamIO.pos被定义Position.int为某种整数类型.
但是,在支持标准的完整I/O堆栈的SML系统中,您应该能够使用较低的I/O层合成以下搜索功能:
(* seekIn : BinIO.instream * Position.int -> unit *)
fun seekIn(instream, pos) =
case BinIO.StreamIO.getReader(BinIO.getInstream instream) of
(reader as BinPrimIO.RD{setPos = SOME f, ...}, _) =>
( f pos;
BinIO.setInstream(instream,
BinIO.StreamIO.mkInstream(reader, Word8Vector.fromList[]))
)
| (BinPrimIO.RD{name, ...}, _) =>
raise IO.Io{
name = name,
function = "seekIn",
cause = IO.RandomAccessNotSupported
}
Run Code Online (Sandbox Code Playgroud)
使用它像:
val file = BinIO.openIn "filename"
val _ = seekIn(file, 200)
val bin = BinIO.inputN(file, 1000)
Run Code Online (Sandbox Code Playgroud)
如果需要从Word8Vector转换为字符串:
val s = Byte.bytesToString bin
Run Code Online (Sandbox Code Playgroud)
你也可以为out流做同等的事情.
[1] http://standardml.org/Basis/bin-io.html#BIN_IO:SIG:SPEC