【问题标题】:Use ellipsis (...) in recurent function calls [duplicate]在重复的函数调用中使用省略号(...)[重复]
【发布时间】:2018-07-30 16:03:47
【问题描述】:

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

我的函数示例:

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

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

【问题讨论】:

  • vfprintf
  • man stdarg :: #include <stdarg.h> void va_start(va_list ap, last);
  • (为了您的搜索乐趣,它被称为可变参数,而不是省略号)

标签: c ellipsis


【解决方案1】:

使用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);
    }
}

【讨论】:

  • @spectras,确实如此。 "如果在从函数返回之前没有调用 va_end,则结果是未定义的。。修复了这个问题。
【解决方案2】:

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

您通常做的是使用显式参数列表 (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__ 来引用变量参数列表,但这在函数中不可用。

【讨论】:

  • 有可能,我做过一次,忘记函数名了。
  • @PeterPolak 这听起来有点像Fermat
【解决方案3】:

你不能直接做;你必须创建一个带有 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

【讨论】:

    猜你喜欢
    • 2017-01-21
    • 1970-01-01
    • 2016-11-20
    • 2017-06-19
    • 2018-02-01
    • 2020-07-29
    • 2018-10-06
    • 2014-09-16
    相关资源
    最近更新 更多