Pass varargs to printf [duplicate]

*爱你&永不变心* 提交于 2019-12-03 06:36:15

Use vprintf, which is declared as:

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

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

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).

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

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);

The method you are looking for is vfprintf or possible vprintf (unclear which by your question)

This is essentially the implementation of printf that allows a va_list to be explicitly passed in as a parameter. So in your method you can create the va_list for your method parameters and forward it onto vfprintf

void log(FILE* f, const char* format, ...) { 
  va_list args;
  va_start (args, format);
  vfprintf (f, format, args);
  va_end (args);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!