View Category

Read the contents of a file into a string

let read_file f =
let ic = open_in f in
let n = in_channel_length ic in
let s = String.create n in
really_input ic s 0 n;
close_in ic;

let file_contents = read_file "file.txt"

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
let () =
let ic = open_in Sys.argv.(1) in
let i = ref 1 in
while true do
Printf.printf "%d> %s\n" !i (input_line ic);
incr i
with End_of_file ->
close_in ic
let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None

let () =
let ic = open_in Sys.argv.(1) in
let rec aux i =
match input_line_opt ic with
| Some line ->
Printf.printf "%d> %s\n" i line;
aux (succ i)
| None ->
close_in ic
aux 1

Write a string to a file

let cout = open_out filename in
let co = Format.formatter_of_out_channel cout in
Format.fprintf co "%s\n" text_to_write;
close_out cout
with Sys_error _ as e ->
Format.printf "Cannot open file \"%s\": %s\n" filename (Printexc.to_string e)

Append to a file

let () =
let oc =
[Open_wronly; Open_creat; Open_append; Open_text] 0o666 "test.txt" in
output_string oc "This line appended to file!\n";
close_out oc

Process each file in a directory

let process dir file =
if not (Sys.is_directory (Filename.concat dir file))
then print_endline file

let () =
let dir = "." in
let files = Sys.readdir dir in
Array.iter (process dir) files

Process each file in a directory recursively

let rec recurse_dir dir f =
let filenames = Sys.readdir dir in
Array.iter (fun name ->
let fullname = Filename.concat dir name in
if Sys.is_directory fullname then
recurse_dir fullname f
f fullname
) filenames
recurse_dir (Sys.getenv "HOME") print_endline ;;