Hi there!

Le 2011-06-21 13:03 +0700, Nguyen Tran Nhan a écrit :
> i think vsnprintf and something like va_list will help you.
> [...]

This is a perfectly correct way, but I would make a few changes.

> void dubPrint(FILE *fp, const char *format, ...)
> {
>     int buf_size = 1024;
>     char *buf = new char[buf_size];

It would be more efficient to use static variables here, so the
allocated space would be kept over calls => less time consuming
malloc/free calls. That is something like this:

        static int buf_size = 1024;
        static char *buf = NULL;

        if (buf == NULL) {
                buf = (char *)malloc(buf_size * sizeof(char));
        }

>     va_list args;
> 
>     va_start(args, format);
>     while (vsnprintf(buf, buf_size, format, args) >= buf_size) {
>         delete[] buf;
>         buf_size *= 2;
>         buf = new char[buf_size];

Here, instead of freeing and then allocating memory again you would
use the realloc function which knows ways to optimize the reallocation
when knowing the already allocated space. That is something like this:

        ... {
                buf_size *= 2;
                buf = (char *)realloc(buf, buf_size * sizeof(char));
        }

>     }
>     va_end(args);
> 
>     printf("%s\n", buf);
>     fprintf(fp, "%s\n", buf);

Here, I would use some non formating function instead, to not lost any
time in formating something that doesn't have to. That is something
like this:

        fputs(buf, stdin);
        fputs(buf, fp);

It should be noted that fputs doesn't add a trailing newline, which
should be placed in the format string instead, IMHO.

> 
>     fflush(fp);
> }

I would rather not flush the output at every print, since it's quite
inefficient. This work should be left to the calling program instead,
which would optimize it by sending a batch of print and flushing only
at the right moment (eg just before asking user interaction).

Cheers, J.C.
-- 
Jean Christophe ANDRÉ  —  Coordonnateur des infrastructures techniques
Agence universitaire de la Francophonie (AUF)  —   http://www.auf.org/
✉ : AUF, 21 Lê Thánh Tông, T.T. Hoàn Kiếm, Hà Nội, Việt Nam
℡ : +84 4 38247382  ✦  ℻ : +84 4 38247383  ✦  Cellul. : +84 91 3248747
⎧Note personnelle: merci d'éviter de m'envoyer des fichiers Microsoft⎫
⎩Office, cf http://www.gnu.org/philosophy/no-word-attachments        ⎭
_______________________________________________
POST RULES : http://wiki.hanoilug.org/hanoilug:mailing_list_guidelines
_______________________________________________
HanoiLUG mailing lists: http://lists.hanoilug.org/
HanoiLUG wiki: http://wiki.hanoilug.org/
HanoiLUG blog: http://blog.hanoilug.org/

Trả lời cho