开发者

Print Value to File

i was not able to print an a value (float) to a file with the OCaml lenguage. How can i do? If you know how, can you show me a littl开发者_StackOverflow社区e example?

Thank you advance and have a good day!


Printf.fprintf allows direction to an out_channel, in your case a file. Reasonably, you'd open the file for writing first, and pass around that channel.

Printf.fprintf (open_out "file.txt") "Float Value of %f" 1.0


If you want to print the textual representation of a float to a file, perhaps the simplest thing to do is:

output_string outf (string_of_float myfloat)

If you want to print the float to the console, you can use

print_string (string_of_float myfloat)

Of course, Printf.printf can also do that and more, so it is worth knowing it.

If you want to output the binary representation of a float, things are more complicated. Since a float value is represented as an IEEE 754 double, it is 8 bytes long which can be written in different orders depending on the platform. In the case of little-endian order, as is normal in X86, you can use the following:

let output_float_le otch fv =
  let bits = ref (Int64.bits_of_float fv) in
  for i = 0 to 7 do
    let byte = Int64.to_int (Int64.logand !bits 0xffL) in
    bits := Int64.shift_right_logical !bits 8;
    output_byte otch byte
  done

The float value so written can be read back with the following:

let input_float_le inch =
  let bits = ref 0L in
  for i = 0 to 7 do
    let byte = input_byte inch in
    bits := Int64.logor !bits (Int64.shift_left (Int64.of_int byte) (8 * i))
  done;
  Int64.float_of_bits !bits

This has the advantage of being a very compact way to exactly preserve floats in a file, that is, what you write will be read back exactly as it originally was. For example, I did this in the interactive top-level:

# let otch = open_out_bin "Desktop/foo.bin" ;;
val otch : out_channel = <abstr>
# output_float_le otch 0.5 ;;
- : unit = ()
# output_float_le otch 1.5 ;;
- : unit = ()
# output_float_le otch (1. /. 3.) ;;
- : unit = ()
# close_out otch ;;
- : unit = ()
# let inch = open_in_bin "Desktop/foo.bin" ;;
val inch : in_channel = <abstr>
# input_float_le inch ;;
- : float = 0.5
# input_float_le inch ;;
- : float = 1.5
# input_float_le inch ;;
- : float = 0.333333333333333315
# close_in inch ;;
- : unit = ()

and as you can see I got back exactly what I put in the file. The disadvantage of this form of writing floats to files is that the result is not human-readable (indeed, the file is binary by definition) and you lose the possibility to interoperate with other programs, like Excel for instance, which in general exchange data in human-readable textual form (CSV, XML, etc.).


Did you try printf?

let a = 4.0

printf "my float value: %f" a

Cf the doc inria and don't forget to open the module

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜