Prints formatted data to a stream using a variable length argument list.
Include
<stdio.h>
<stdarg.h>
Prototype
int vfprintf(FILE *stream, const char *format,
va_list ap);
Arguments
stream
|
pointer to the open stream |
format
|
format control string |
ap
|
pointer to a list of arguments |
Return Value
Returns number of characters generated or a negative number if an error occurs.
Remarks
The format argument has the same syntax and use that it has
in printf
.
To access the variable length argument list, the
ap
variable must be initialized by the macro
va_start
and may be reinitialized by additional calls
to va_arg
. This must be done before the
vfprintf
function is called. Invoke
va_end
after the function returns. For more details,
see stdarg.h
.
This function requires a heap.
Example
#include <stdio.h> /* for vfprintf, fopen, */
/* fclose, printf, */
/* FILE, NULL */
#include <stdarg.h> /* for va_start, */
/* va_list, va_end */
FILE *myfile;
void errmsg(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(myfile, fmt, ap);
va_end(ap);
}
int main(void)
{
int num = 3;
if ((myfile = fopen("afile.txt", "w")) == NULL)
printf("Cannot open afile.txt\n");
else
{
errmsg("Error: The letter '%c' is not %s\n", 'a',
"an integer value.");
errmsg("Error: Requires %d%s%c", num,
" or more characters.", '\n');
}
fclose(myfile);
}
Example Output
Contents of afile.txt
:
Error: The letter 'a' is not an integer value.
Error: Requires 3 or more characters.