将varargs传递给printf [英] Pass varargs to printf

查看:73
本文介绍了将varargs传递给printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个辅助函数log,该函数基本上执行以下操作:

I'd like to have a helper function log that essentially does the following:

log(file, "array has %d elements\n", 10);
// writes "2014-02-03 16:33:00 - array has 10 elements" to &file

我的时间部分减少了,而文件写入部分减少了.但是,问题在于log—的方法签名本身.我该放些什么? 表示printf声明以...关键字结尾,但是如何在函数中使用它呢?

I have the time portion down, and I have the file writing portion down. However, the problem is the method signature itself for log — what should I put? This says that the printf declaration ends with the ... keyword, but how can I use this in my function?

void log(FILE *f, const char * format, ...) // how would I pass ... to fprintf?


让我编辑,其中包含更多信息.


Let me EDIT this to include a bit more information.

我有一个const char * now (),它返回的字符串形式为"2014-02-03 16:33:00".我想像这样传递另一个格式字符串.这两个语句应该等效:

I have a const char * now () that returns a string of the form "2014-02-03 16:33:00." I would like to pass another format string in like this. The two statements should be equivalent:

log(file, "array has %d elements\n", 10);
fprintf(file, "%s - array has %d elements\n", now(), 10);

我知道vfprintf允许我传递va_list,但是如何将now()作为第一个参数,之前?

I know that vfprintf allows me to pass a va_list, but how can I put the now() as the first argument, before all the others?

推荐答案

使用vprintf,它声明为:

int vprintf(const char *format, va_list ap);

在您的log函数中,调用va_start以获得va_list值,然后将该值传递给vprintf.

In your log function, invoke va_start to obtain a va_list value, then pass that value to vprintf.

由于您的log函数采用了FILE*参数,因此您可能希望使用vfprintf而不是vprintf(并且可能会更新您的问题以询问有关fprintf而不是printf的问题).

Since your log function takes a FILE* argument, you'll probably want to use vfprintf rather than vprintf (and perhaps update your question to ask about fprintf rather than printf).

顺便说一句,您可能想重新考虑使用名称log;这是在<math.h>中声明的标准函数的名称.

Incidentally, you might want to reconsider using the name log; that's the name of a standard function declared in <math.h>.

反映您更新的问题,您可以通过直接调用fprintflog中打印时间戳:

Reflecting your updated question, you can print the timestamp inside log by calling fprintf directly:

va_list(args);
fprintf(f, "%s - ", now());
va_start(args, format);
vfprintf(f, format, args);

这篇关于将varargs传递给printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆