Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between the printf and vprintf function families, and when should I use one over the other?

Tags:

c

I understand that the difference between the printf, fprintf, sprintf etc functions and the vprintf, vfprintf, vsprintf etc functions has to do with how they deal with the function arguments. But how specifically? Is there really any reason to use one over the other? Should I just always use printf as that is a more common thing to see in C, or is there a legitimate reason to pick vprintf instead?

like image 416
Carson Myers Avatar asked Sep 28 '09 07:09

Carson Myers


People also ask

What is Vprintf?

The vprintf() function returns the total number of characters written. In case of an error, the function returns a negative number.

What is Vfprintf in C?

The C library function int vfprintf(FILE *stream, const char *format, va_list arg) sends formatted output to a stream using an argument list passed to it.


2 Answers

printf() and friends are for normal use. vprintf() and friends are for when you want to write your own printf()-like function. Say you want to write a function to print errors:

int error(char *fmt, ...) {     int result;     va_list args;     va_start(args, fmt);     // what here?     va_end(args);     return result; } 

You'll notice that you can't pass args to printf(), since printf() takes many arguments, rather than one va_list argument. The vprintf() functions, however, do take a va_list argument instead of a variable number of arguments, so here is the completed version:

int error(char *fmt, ...) {     int result;     va_list args;     va_start(args, fmt);     fputs("Error: ", stderr);     result = vfprintf(stderr, fmt, args);     va_end(args);     return result; } 
like image 106
Chris Lutz Avatar answered Sep 22 '22 11:09

Chris Lutz


You never want to use vprintf() directly, but it's incredibly handy when you need to e.g. wrap printf(). For these cases, you will define the top-level function with variable arguments (...). Then you'll collect those into a va_list, do your processing, and finally call vprintf() on the va_list to get the printout happening.

like image 35
unwind Avatar answered Sep 22 '22 11:09

unwind