简体   繁体   English

为需要可变数量参数的函数编写替换(c编程)

[英]writing a replacement for a function which takes a variable number of parameters (c programming)

I'm looking to write a function to replace fprintf 我正在寻找编写替换fprintf的函数

int fprintf ( FILE * stream, const char * format, ... );

I'm not sure how to define a function such as this, because, after the format parameter, this function takes a variable number of parameters. 我不确定如何定义这样的函数,因为在format参数之后,此函数需要可变数量的参数。 Specifically, it takes at least as many additional arguments as were specified in the format. 具体来说,它至少接受与格式中指定的一样多的其他参数。

UPDATE I found a resource on the subject ( http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html ), but the example doesn't seem to compile under Linux, the OS that I'm using. 更新我找到了关于该主题的资源( http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html ),但是该示例似乎无法在我正在使用的OS Linux下进行编译。

An example of a replacement for fprintf which just calls fprintf would be helpful. 一个仅调用fprintf的替代fprintf的示例将很有帮助。

This isn't homework. 这不是功课。 I'm just a beginner who is trying to learn how to program in his free time. 我只是一个初学者,他试图在业余时间学习如何编程。 Thanks! 谢谢!

Instead of calling fprintf directly, you will need to call vfprintf instead. 无需直接调用fprintf ,而是需要调用vfprintf For example: 例如:

#include <stdarg.h>
int myfprintf(FILE *stream, const char *format, ...) {
    va_list args;
    va_start(args, format);
    int r = vfprintf(stream, format, args);
    va_end(args);
    return r;
}

In the standard library, every function that takes varargs ( ... ) also has a v version of the same function that takes a va_list parameter. 在标准库中,每个采用varargs( ... )的函数也具有采用va_list参数的同一函数的v版本。 Since you can't construct arguments to pass to ... dynamically, you need to use the v variant to pass on the varargs. 由于您无法构造要动态传递给...参数,因此需要使用v变量来传递varargs。

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

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