如何将“...”(可变长度arg列表)通过我的函数传递给另一个? [重复]

时间:2021-03-19 20:23:49

This question already has an answer here:

这个问题在这里已有答案:

Old client code:

旧客户代码:

printf("foo: %d, bar: %s.\n", f, b);

What I'd like to replace that printf (& 100's others like it) with:

我想用以下内容替换printf(&100的其他人喜欢)

my_printf(ctrl1, ctrl2, "foo: %d, bar: %s.\n", f, b);

Implementation of my_printf

my_printf的实现

void my_printf(CtrlT1 c1, Ctrl c2, char* fmt, ...) {
/* Do stuff with c1 & c2 */
   fprintf(log, fmt, **WHAT_GOES_HERE**);
}

What I've tried so far

到目前为止我尝试过的

It seems like there ought to be a simple, direct way to pass the list of arguments associated with ... through to fprintf. I tried fprintf(log, fmt, ...); but the compiler complains, "syntax error before '...' token".

似乎应该有一种简单,直接的方法将与...相关的参数列表传递给fprintf。我试过fprintf(log,fmt,...);但编译器抱怨说,“'''令牌之前的语法错误”。

I also tried: va_list ap; va_start(ap, fmt); fprintf(log, fmt, ap);

我也尝试过:va_list ap; va_start(ap,fmt); fprintf(log,fmt,ap);

The call with the va_list compiles and even runs without coring, but what's being passed to printf is plainly not the same thing as what was passed into my function as ..., as may be judged by the output (representation of non-printing char).

使用va_list进行的调用可以编译甚至运行而不进行核化,但传递给printf的内容与传递给我的函数的内容明显不同......可以通过输出判断(非打印字符的表示) )。

If push comes to shove, I could probably walk through the contents of the va_list by brute-force but that seems stupid. Is there no simple token or syntax to pass that ... through?

如果推动推动,我可能会通过蛮力走过va_list的内容,但这似乎很愚蠢。是否没有简单的令牌或语法来传递...通过?

1 个解决方案

#1


5  

This isn't a general solution, but for the stdio functions, look at the ones that start with the letter v, such as vfprintf. They take a va_list as their last parameter, instead of the ....

这不是一般解决方案,但对于stdio函数,请查看以字母v开头的函数,例如vfprintf。他们将va_list作为最后一个参数,而不是....

void my_printf(CtrlT1 c1, Ctrl c2, char* fmt, ...) {
    /* Do stuff with c1 & c2 */
    va_list ap;
    va_start (ap, fmt);
    vfprintf (log, fmt, ap);
    va_end (ap);
}

#1


5  

This isn't a general solution, but for the stdio functions, look at the ones that start with the letter v, such as vfprintf. They take a va_list as their last parameter, instead of the ....

这不是一般解决方案,但对于stdio函数,请查看以字母v开头的函数,例如vfprintf。他们将va_list作为最后一个参数,而不是....

void my_printf(CtrlT1 c1, Ctrl c2, char* fmt, ...) {
    /* Do stuff with c1 & c2 */
    va_list ap;
    va_start (ap, fmt);
    vfprintf (log, fmt, ap);
    va_end (ap);
}