Writes formatted output using a variable argument list object
#include <stdio.h>
#include <stdarg.h>
int vfprintf ( FILE * restrict fp , const char * restrict format ,
va_list argptr );
int vprintf ( const char * restrict format , va_list argptr );
int vsprintf ( char * restrict buffer , const char * restrict format ,
va_list argptr );
int vsnprintf ( char * restrict buffer , size_t n ,
const char * restrict format , va_list argptr ); (C99)
The functions vfprintf( ), vprintf( ), vsprintf( ), and vsnprintf( ) work in the same way as fprintf( ), printf( ), sprintf( ), and snprintf( ), respectively, except that their last argument, argptr, is a variable-argument list object with type va_list. The program must initialize this object by calling the va_start( ) macro before calling the vfprintf( ), vprintf( ), vsprintf( ), or vsnprintf( ) function, and must call the va_end( ) macro after the function returns. Because these functions use the va_arg( ) macro internally to advance argptr through the argument list, its value is indeterminate after the vfprintf( ), vprintf( ), vsprintf( ), or vsnprintf( ) function call has returned.
Like the fprintf( ) and printf( ) functions, vfprintf( ) and vprintf( ), return the number of characters written to the output stream. The function vsprintf( ) returns the number of characters written to the string buffer, not counting the terminator character; and vsnprintf( ) returns the number of characters that would have been written to the string buffer if the parameter n had been sufficiently large, again not counting the terminator character. Example
// write_log appends a line to the log file associated with the
// FILE pointer fp_log.
// The format string and optional arguments are the same as for printf( ).
void write_log(const char *function_name, unsigned int line_num,
const char *format_str, ...)
{
if ( fp_log == NULL)
return;
time_t timestamp = time(NULL);
va_list argptr;
// Set argptr to the first optional argument:
va_start( argptr, format_str);
// First print the timestamp, function name, and line number:
fprintf( fp_log, "%.8s %s (line %u): ",
ctime(×tamp)+11, function_name, line_num);
// Then print the rest of the message:
vfprintf( fp_log, format_str, argptr);
va_end(argptr);
}
void myFunc( int param)
{
write_log( _ _func_ _, _ _LINE_ _, "param = %d\n", param);
/* ... */
}
Calling myFunc( ) in this example with the argument value 777 results in the following log file entry: 13:32:44 myFunc (line 62): param = 777 See Alsova_start( ), va_arg( ), va_copy( ) and va_end( ); fprintf( ), printf( ), sprintf( ), and snprintf( ); vfwprintf( ), vwprintf( ), and vswprintf( ) |