How to use parameters const char *format in custom printf

Viewed 658

I'm looking for a function that print log information, in order to debug my program. This function must look at a boolean and decide if write the log in a file or to the console.

int useFile;
int log_informations( ? )
{
  if(useFile)
  {
     // open/close FILE *pf omitted
     fprintf(pf, ? );
  }
  else
  {
    printf( ? );
  }
  return 0;
}

int main()
{
  int answer = 42;
  log_informations("The answer is %d.", answer);
  return 0;
}

Can you help me with the parameter? I did not found any reference.

NB: In this question I made things clear and simpler as they were in my context, so I do not need workaround but, possibly, a simple answer.

Thank you in advance ;)

1 Answers

As other mentioned, you don't need to actually write a function. A macro could help here:

#define LOG(fmt, ...)    fprintf(logToFile ? fileLogger : stdout, fmt, ##__VA_ARGS__)

To answer your question you can look at how printf and vprintf work:

int printf(const char *format, ...);
int vprintf(const char *format, va_list arg);

printf is a variadic function and you want to provide your own version that wraps vprintf and vfprintf.

#include <stdarg.h> // needed for va_list, va_start, and va_end.

int my_printf(const char *format, ...)
{
    va_list ap;
    int ret;

    va_start(ap, format);
    if (useFile) ret = vfprintf(pf, format, ap);
    else ret = vprintf(format, ap);
    va_end(ap);

    return ret;
}

EDIT: as @phuclv mentioned, if you want to include file, line, and/or function information in your log a macro is the only way. For example, for appending file and line information you could do something like this:

#define LOG(fmt, ...)    fprintf(logToFile ? fileLogger : stdout, __FILE__ ":" STRINGIFY(__LINE__) " " fmt, ##__VA_ARGS__)

#define STRINGIFY_HELPER(x) #x
#define STRINGIFY(x)        STRINGIFY_HELPER(x)

You need STRINGIGY for __LINE__ because it is an int.

Related