LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   is a printf wrapper possible? (https://www.linuxquestions.org/questions/programming-9/is-a-printf-wrapper-possible-374948/)

Thinking 10-20-2005 03:10 AM

is a printf wrapper possible?
 
hiho@ll

is it possible to write a wrapper for printf

what i want:

myprintf("%s%d","test",5);

void myprintf(char *fmt,...){
var_list ap;
va_start(ap,fmt);

openlogfile();
printf("HMM ");

printf(fmt,ap); // << doesn't work, but how can i do this?

closelogfile();
}

in the above example (well, i tried without openlogfile, etc.) i got HM-1073745612

1. can it work?
2. how?
3. the next step i'm thinking about is a function, which calls another function depending on the argument
this means i want to write a wrapper for every possible function
this includes that one argument of my wrapper function is a function pointer!
void* mywrapper(void* (*func)(void*,...),...);
is this possible and how?

why i want to do this?
1. i'm interested if it works
2. maybe i can do some cool log functions
3. or my own memory management class (maybe )

thx@ll:D

Wim Sturkenboom 10-20-2005 08:45 AM

Re: is a printf wrapper possible?
 
Quote:

Originally posted by Thinking
void myprintf(char *fmt,...){
var_list ap;
va_start(ap,fmt);

openlogfile();
printf("HMM ");

printf(fmt,ap); // << doesn't work, but how can i do this?

closelogfile();
}

in the above example (well, i tried without openlogfile, etc.) i got HM-1073745612
You use the wrong function for the printf; look at the vprintf functions.
Code:

void logit(char *filename, int verbose, int code, char *msg, ...)
{
va_list fmtargs;
char buffer[1024];

  va_start(fmtargs,msg);
  vsnprintf(buffer,sizeof(buffer)-1,msg,fmtargs);
  va_end(fmtargs);
  printf("%s",buffer);
  if(code!=0)
    printf("[%d]%s\n",errno,strerror(code));

  // do more stuff here (like write to file)
}

This is a stripped version of a logging function that I use and it prints correctly

call e.g. with logit("logfile",0,errno,"%s:%d\n",string_1,int_1);

Thinking 10-21-2005 07:44 AM

thx!!
seems to work

it's very long since i last viewed the man page of printf :D


All times are GMT -5. The time now is 03:51 AM.