重复使用可变参数不起作用 [英] Repeated use of a variadic function argument doesn't work

查看:110
本文介绍了重复使用可变参数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,试图将东西记录到控制台和日志文件,但它不工作。第二次使用可变长度参数将垃圾写入控制台。有任何想法吗?

I have a function that tries to log stuff to the console and also to a log file, but it doesn't work. The second use of the variable length argument gives garbage written to the console. Any ideas?

    void logPrintf(const char *fmt, ...) {
        va_list ap;    // log to logfile
        va_start(ap, fmt);
        logOpen;
        vfprintf(flog, fmt, ap);
        logClose;
        va_end(ap);
        va_list ap2;   // log to console
        va_start(ap2, fmt);
        printf(fmt, ap2);
        va_end(ap2);
    }


推荐答案

同样 va_list 两次,也不会得到两次。您必须使用 va_copy()

You can't use the same va_list twice, nor get it twice. You have to use va_copy():

va_list ap, ap2;
va_start(ap, fmt);
va_copy(ap2, ap);
// ... with ap
// ... with ap2
va_end(ap2);
va_end(ap);

在某些系统上, __ va_copy()可用;您可能想使用 #ifdef 。如果你使用glib,它会为你使用 G_VA_COPY()

On some systems, __va_copy() is available instead; you may want to use #ifdef for that. If you use glib, it does that for you using G_VA_COPY().

这篇关于重复使用可变参数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆