Pass varargs to printf [duplicate]

左心房为你撑大大i 提交于 2019-12-03 16:48:32

问题


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

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.

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

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?


回答1:


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



回答2:


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

  • http://www.cplusplus.com/reference/cstdio/vfprintf/
  • http://www.cplusplus.com/reference/cstdio/vprintf/

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


来源:https://stackoverflow.com/questions/21540778/pass-varargs-to-printf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!