The Scanf
module appears to behave somewhat
counterintuitively in that it doesn’t respect the state of the
underlying channel:
(* prepare test data *)
let () =
let oc = open_out "test.txt" in
output_string oc "abcdefghij\n";
close_out oc
;;
let ic = open_in "test.txt"
(* ic at offset 0: “ab…” *)
let () =
let sc = Scanf.Scanning.from_channel ic in
let s = Scanf.bscanf sc "%2s" (fun s -> s) in
Printf.eprintf "read [%s]\n" s (* -> [ab] *)
;; (* sc out of scope at this point *)
(* hint: close ic here and reopen for expected result *)
seek_in ic 4
(* ic at offset 4: “ef…” *)
let () =
let sc = Scanf.Scanning.from_channel ic in
let s = Scanf.bscanf sc "%2s" (fun s -> s) in
Printf.eprintf "read [%s]\n" s (* -> [cd] ‽ *)
;;
close_in ic
Apparently the internal buffer of Scanning.t
survives it
unless the channel is recreated. Is there another way to force a
resync? The docs
claim that “Reading starts at current reading position of ic.”
I’d appreciate a pointer to where exactly this behavior is documented.