9) Basic input/output
9) Basic input/output
9) Basic input/output
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
62 CHAPTER 9. BASIC INPUT/OUTPUT<br />
9.3 Input<br />
These <strong>input</strong> primitives flush the standard <strong>output</strong> and read from the standard <strong>input</strong>:<br />
#read_line;;<br />
- : unit -> string = <br />
#read_int;;<br />
- : unit -> int = <br />
#read_float;;<br />
- : unit -> float = <br />
Because of their names and types, these functions do not need further explanation.<br />
9.4 Channels on files<br />
When programs have to read from or print to files, it is necessary to open and close channels on<br />
these files.<br />
9.4.1 Opening and closing channels<br />
Opening and closing is performed with the following functions:<br />
#open_in;;<br />
- : string -> in_channel = <br />
#open_out;;<br />
- : string -> out_channel = <br />
#close_in;;<br />
- : in_channel -> unit = <br />
#close_out;;<br />
- : out_channel -> unit = <br />
The open_in function checks the existence of its filename argument, and returns a new <strong>input</strong><br />
channel on that file; open_out creates a new file (or truncates it to zero length if it exists) and<br />
returns an <strong>output</strong> channel on that file. Both functions fail if permissions are not sufficient for<br />
reading or writing.<br />
Warning:<br />
• Closing functions close their channel argument. Since their behavior is unspecified on already<br />
closed channels, anything can happen in this case!<br />
• Closing one of the standard IO channels (std_in, std_out, std_err) have unpredictable<br />
effects!