C语言 使用 va_list 调用 printf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5977326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:38:07  来源:igfitidea点击:

call printf using va_list

cprintfvariadic-functions

提问by Alex F

void TestPrint(char* format, ...)
{
    va_list argList;

    va_start(argList, format);
    printf(format, argList);
    va_end(argList);
}


int main()
{
    TestPrint("Test print %s %d\n", "string", 55);
    return 0;
}

I need to get:

我需要得到:

Test print string 55

Actually, I get garbage output. What is wrong in this code?

实际上,我得到了垃圾输出。这段代码有什么问题?

回答by Oliver Charlesworth

Use vprintf()instead.

使用vprintf()来代替。

回答by onteria_

Instead of printf, I recommend you try vprintf instead, which was created for this specific purpose:

我建议您不要尝试使用 printf,而是尝试使用 vprintf,它是为此特定目的而创建的:

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

void errmsg( const char* format, ... )
{
  va_list arglist;

  printf( "Error: " );
  va_start( arglist, format );
  vprintf( format, arglist );
  va_end( arglist );
}

int main( void )
{
  errmsg( "%s %d %s", "Failed", 100, "times" );
  return EXIT_SUCCESS;
}

Source: http://www.qnx.com/developers/docs/6.5.0/index.jsp?topic=/com.qnx.doc.neutrino_lib_ref/v/vprintf.html

来源:http: //www.qnx.com/developers/docs/6.5.0/index.jsp?topic=/com.qnx.doc.neutrino_lib_ref/ v/vprintf.html

回答by CliffordVienna

As others have pointed out already: In this case you should use vprintfinstead.

正如其他人已经指出的那样:在这种情况下,您应该vprintf改用。

But if you really want to wrap printf, or want to wrap a function that does not have a v...version, you can do that in GCC using the non-standard __builtin_applyfeature:

但是如果你真的想要 wrap printf,或者想要包装一个没有v...版本的函数,你可以在 GCC 中使用非标准__builtin_apply特性来做到这一点:

int myfunction(char *fmt, ...)
{
    void *arg = __builtin_apply_args();
    void *ret = __builtin_apply((void*)printf, arg, 100);
    __builtin_return(ret);
}

The last argument to __builtin_applyis the max. total size of the arguments in bytes. Make sure that you use a value here that is large enough.

的最后一个参数__builtin_apply是最大值。参数的总大小(以字节为单位)。确保在此处使用足够大的值。

回答by Constantinius

This is not how you use printf(). If you want to use va_lists, use vprintf()instead. Look herefore reference.

这不是您使用printf(). 如果要使用va_lists,请vprintf()改用。看看这里作为参考。