Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Format question
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: David Brown <caml-list@d...>
Subject: Re: [Caml-list] Format question
On Wed, Nov 06, 2002 at 05:49:41PM -0500, Oleg wrote:

> Is it possible to define a printf that automatically flushes stdout?
> 
> let my_printf x = Printf.printf x; flush stdout;;
> 
> my_printf "%i" 3;;

The problem is that printf takes multiple arguments, or at least appears
to.  You could try:

let my_printf x =
  let res = Printf.printf x in
  flush stdout;
  res

which would be correctly typed, but the flush would happen right before
the first format string.

Really, you would have to grab the definition of printf from the source,
and change it to do what you want.  This makes it a lot less portable.

let my_fprintf chan fmt =
  let fmt = (Obj.magic fmt : string) in
  let len = String.length fmt in
  let rec doprn i =
    if i >= len then begin flush chan; Obj.magic () end else
    match String.unsafe_get fmt i with
    | '%' -> Printf.scan_format fmt i cont_s cont_a cont_t
    | c   -> output_char chan c; doprn (succ i)
  and cont_s s i =
    output_string chan s; doprn i
  and cont_a printer arg i =
    printer chan arg; doprn i
  and cont_t printer i =
    printer chan; doprn i
  in doprn 0

let my_printf fmt = my_fprintf stdout fmt
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners