在recurent函数调用中使用省略号(...)

时间:2018-02-20 10:14:44

标签: c ellipsis

我想用省略号参数编写一个函数writelog(),它应该将相同的省略号参数转发给另一个函数。怎么做?

我的功能示例:

void writetolog(char *format, ...)
{
    FILE *file;
    if ((file = fopen(LOG_FILE, "a")) != NULL)
    {
        fprintf(file, format, ...);
        fclose(file);
    }
}

函数fprintf()应该具有与函数writetolog()相同的省略号参数。

3 个答案:

答案 0 :(得分:4)

这是不可能的,...参数不能直接传递。

您通常使用显式参数列表(va_list)参数实现最低层,并以此方式解决。

在您的情况下,如果最低层是标准库的打印,那么您需要使用包含函数参数的显式va_list来调用vfprintf()

void writetolog(const char *format, ...)
{
    FILE * const file = fopen(LOG_FILE, "a");
    if (file != NULL)
    {
        va_list args;
        va_start(args, format);
        vfprintf(file, format, args);
        va_end(args);
        fclose(file);
    }
}

请注意,在C宏中,您可以使用特殊符号__VA_ARGS__来引用变量参数列表,但这在函数中不可用。

答案 1 :(得分:4)

使用vfprintf功能:

#include <stdarg.h>             // vararg macros

void writetolog(char *format, ...)
{
    FILE *file;
    if ((file = fopen(LOG_FILE, "a")) != NULL)
    {
        va_list args;
        va_start (args, format);

        vfprintf(file, format, args);
        fclose(file);
        va_end(args);
    }
}

答案 2 :(得分:0)

你不能直接这样做;你必须创建一个带有va_list的函数:

#include <stdarg.h>

static void exampleV(int b, va_list args);

void example(int a, int b, ...)
{
    va_list args;
    va_start(args, b);
    exampleV(b, args);
    va_end(args);
}

void exampleB(int b, ...)
{
    va_list args;
    va_start(args, b);
    exampleV(b, args);
    va_end(args);
}

static void exampleV(int b, va_list args)
{
    ...whatever you planned to have exampleB do...
    ...except it calls neither va_start nor va_end...
}

取自Passing variable arguments to another function that accepts a variable argument list