(* This program is meant to demonstrate simple I/O for OCaml
- MAT - 02192009
Its intended usage is to take a filename as a parameter when executing a program,
e.g. ./io myFile.txt
that consists of one number per line. The program then sorts the list and outputs a file represenative
of the sorted list with one number per line. Lines in the input file that are not integers will cause an exception to be thrown.
*)
open Printf
let rec input_lines file =
match try [input_line file] with End_of_file -> [] with
[] -> []
| line -> line @ input_lines file
let inFile =
try Sys.argv.(1) with noFileName -> "Specify a filename for input for the second argument, e.g. ./io foo.txt";;
let inputChannel = open_in inFile;;
let stringList = (input_lines inputChannel);;
let numbers = Array.make (List.length stringList) 0 in
printf "%s\n" "Before: ";
(* This seems excessive but is necessary to change the data type *)
for i=0 to (List.length stringList)-1 do
Array.set numbers i (int_of_string (List.nth stringList i));
printf "%d\n" (Array.get numbers i);
done ;
printf "%s\n" "After: ";
Array.sort compare numbers;
for i=0 to (List.length stringList)-1 do
printf "%d\n" (Array.get numbers i);
done ;
(* Output file *)
let outputStream = open_out inFile in
for i=0 to (Array.length numbers)-1 do
fprintf outputStream "%d\n" (Array.get numbers i);
done;
close_out outputStream;;
Sample data to be put in file specified as first parameter
43
3317
112