简体   繁体   English

函数参数,如C中的printf

[英]Function arguments like printf in C

I want to implement a function Myprintf() that takes arguments like printf() . 我想实现一个函数Myprintf() ,它接受像printf()这样的参数。 Now I am doing this by: 现在我这样做:

sprintf(demoString, "Num=%d String=%s", num, str);
Myprintf(demoString);

I want to replace this function call as: 我想将此函数调用替换为:

Myprintf("Num=%d String=%s", num, str);

How is this possible? 这怎么可能?

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

extern int Myprintf(const char *fmt, ...);

int Myprintf(const char *fmt, ...)
{
    char buffer[4096];
    va_list args;
    va_start(args, fmt);
    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
    va_end(args);
    ...print the formatted buffer...
    return rc;
}

It isn't clear from your question exactly how the output is done; 你的问题并不清楚输出是如何完成的; your existing Myprintf() presumably outputs it somewhere, maybe with fprintf() . 您现有的Myprintf()可能会将其输出到某个地方,可能使用fprintf() If that's the case, you might write instead: 如果是这种情况,您可以改为:

int Myprintf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    int rc = vfprintf(debug_fp, fmt, args);
    va_end(args);
    return rc;
}

If you don't want to use the return value, declare the function as void and don't bother with the variable rc . 如果您不想使用返回值,请将该函数声明为void并且不要使用变量rc

This is a fairly common pattern for ' printf() cover functions'. 这是' printf()封面函数'的一种相当常见的模式。

您需要使用变量参数定义函数 ,并使用vsprintf构建字符串。

The printf and its relatives are in a family of functions called variadic functions and there are macros/functions in the <stddef.h> header in the C standard library to manipulate variadic argument lists. printf及其亲属属于一系列称为可变函数的函数 ,C标准库的<stddef.h>头中有宏/函数来操作可变参数列表。 Look at the GNU docs for examples: How Variadic Functions are Defined and Used . 请查看GNU文档中的示例: 如何定义和使用变量函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM