Reputation: 13
I'm trying to use vfprintf in the following way
vfprintf(fp, buffer, arg);
fp log file that I create using the date and time of the run, a buffer and the rest of the args
fp = fopen(filename, "a");
va_start(arg, message);
vprintf(message, arg); // print stdout
vfprintf(fp, buffer, arg); // print to file
va_end(arg);
fclose(fp);
it works perfectly with numbers and it dies horribly with the error: vfprintf source not found at ....
Does anyone have any idea what I'm doing wrong by any chance?
Upvotes: 1
Views: 1259
Reputation: 136505
You are probably using a 64-bit architecture where variable length arg
can only be passed over once. To make more passes copy arg
using va_copy()
:
va_list arg, arg2;
va_start(arg, message);
va_copy(arg2, arg);
vprintf(message, arg); // print stdout
va_end(arg);
vfprintf(fp, buffer, arg2); // print to file
va_end(arg2);
From man va_arg
:
The va_arg() macro expands to an expression that has the type and value of the next argument in the call. The argument ap is the va_list ap initialized by va_start(). Each call to va_arg() modifies ap so that the next call returns the next argument. The argument type is a type name specified so that the type of a pointer to an object that has the specified type can be obtained simply by adding a * to type.
...
If ap is passed to a function that uses va_arg(ap,type) then the value of ap is undefined after the return of that function.
Upvotes: 3