2

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.

1 Answer 1

1

Just on general design principles, I would say that a call to Scanf.Scanning.from_channel moves responsibility for the channel to the Scanf module. Things aren't guaranteed to work if you go behind the back of the Scanf module and manipulate the channel directly (as you do here with seek_in).

Things work similarly with virtually every layered I/O library that I've used. E.g., you can't use fdopen() from Unix stdio and expect to read data through the FILE abstraction while also manipulating the underlying file descriptor in arbitrary ways.

It might be good if the documentation mentioned these issues (in both cases).

2
  • I’m reading mostly binary with some regular text interspersed, so Scanf isn’t needed most of the time. Commented Feb 18, 2017 at 9:07
  • You could try reading the text into a buffer then use sscanf. In my experience sscanf is easier to use and more dependable than scanning from a channel. I haven't used scanf in production code in decades. If your text is simple you could also just use int_of_string and the like. FWIW. Commented Feb 18, 2017 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.