views:

148

answers:

1

I wrote a short bit of code to simply skip num_lines lines in an input file (printing the lines out for debugging purposes. Here's two things I tried that didn't work:

for i = 0 to num_lines do
  print_endline (fscanf infile "%s" (fun p -> p));
done;;

for i = 0 to num_lines do
  print_endline (fscanf infile "%S\n" (fun p -> p));
done;;

But this one did work:

for i = 0 to num_lines do
  print_endline (fscanf infile "%s\n" (fun p -> p));
done;;

I've been trying to comprehend the documentation on fscanf, but it doesn't seem to be sinking in. Could someone explain to me exactly why the last snippet worked, but the first two didn't?

+3  A: 

"%s" -- Matches everything to next white-space ("\n" here) but never matches "\n"

"%S\n" -- Matches thing that looks like Ocaml strings, then a "\n"

"%s\n" -- Matches everything to next white-space ("\n" here) then "\n". This will act different if there is no trailing "\n" in file or if there is a space before the "\n", etc.

"%s " -- Matches anything up to white-space, and then all trailing white-space including "\n" (or possibly even no white-space). This works because " " means "any white space, possible none", in the format string.

pst