The difference between the printf and vprintf is , vprintf() function takes an extra argument which points to a list of arguments.

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

int vprintf(const char *  format, va_list arg_ptr);
  • vprintf() is used to write custom printf() like function.

practical example of using vprintf

Write your own logging utility which prints file , function , line number with time stamp.

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

void Log (char *format, ...)
{
  va_list args;
  va_start (args, format);
  vfprintf (stdout, format, args);
  va_end (args);
}


time_t curtime;

void hello ()
{
  time (&curtime);
  Log ("%s %s %d time %s ", __FILE__, __func__, __LINE__, ctime (&curtime));
}

int main ()
{
  hello ();
  return 0;
}

Compile and run

bosch@bosch-Inspiron-N5050:~$ gcc main.c -o main
bosch@bosch-Inspiron-N5050:~$ 
bosch@bosch-Inspiron-N5050:~$ ./main 
main.c hello 19 time Sun Aug  6 15:40:05 2017

How it works

void Log (char *format, ...)
{
  va_list args;
  va_start (args, format);
  vfprintf (stdout, format, args);
  va_end (args);
}
  • The function Log(char *format , … ) , … indicates any number of arguments.
  • va_list points to the arguments list.
  • va_start(args, format) initializes args variable to be used with the va_arg and va_end macros.
  • vfprintf (stdout, format, args); prints each argument to the screen.
  • The va_arg, va_end, and va_start macros provide a portable way to access the arguments to a function when the function takes a variable number of arguments.

Ref:

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



Related Contents to follow