Reputation: 125
I want to customize output to a file from my program.
void http_log(char* msg, ...)
{
char* prePend = "Date-Time: %s === ";//Prepended text
size_t len1 = strlen(prePend);
size_t len2 = strlen(msg);
char *s = malloc(len1 + len2 + 1); //The new string
memcpy(s, prePend, len1);
memcpy(s + len1, msg, len2 + 1); // includes terminating null
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
char *dateTime = asctime (timeinfo);//Get the current date time
dateTime[strlen(dateTime) - 1] = 0;//Take away the new line character
va_list args;
va_start( args, msg);
//I think the problem lies here...
fprintf( log_fd, s, dateTime, args);//Print it to the log file. log_fd is already created and opened.
printf(s, dateTime, args);//Prints to screen.
va_end( args);
free( s);
}
I want to add some standard text before the output from http_log(); (The current date in this case). After that i want to add some customizable text that you pass in to the http_log function http_log("This will be appended after the date \n");. and at last i want to be able to use the %s, %d, %ld and so on (Don't know what they are called) like http_log("Connected with IP address %s\n", IP_addres);
My problem is that the values i pass through does not get printed. Should i try to combine the string with the values before i combine the values or... Or is there some other other thing that is wrong with my code??
I'm grateful for all the help && || *pointers
Some C fun :)
Upvotes: 1
Views: 503
Reputation: 540065
You cannot pass the va_list args
to printf()
, but to vprintf()
.
And you cannot combine an "additional argument" dateTime
with the va_list
,
so you have to print them separately:
void http_log(char* msg, ...)
{
char *dateTime = ...;
fprintf(log_fd, "Date-Time: %s === ", dateTime);
printf("Date-Time: %s === ", dateTime);
va_list args;
va_start(args, msg);
vfprintf(log_fd, msg, args);
va_end( args);
va_start(args, msg);
vprintf(msg, args);
va_end( args);
}
Upvotes: 2
Reputation: 3450
I don't think it's possible with only one call to printf()
. Your message and parameters you have to pass to v
version of the print function, vfprintf()
in your case. The date (or whatever you want to generate inside http_log()
) you have to pass to non-v
version of the print function.
Upvotes: 0