Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create function like printf variable argument

Tags:

I was looking to implement an api like printf for my logging. It should be similar to calling printf. For example:

persistent_log(LogType0, "This is buffered writing %d", i); 

I looked into variable argument stuff , but it seems I need to know the number & type of arguments there. so I need more help in that regard.

like image 672
vindyz Avatar asked Aug 11 '11 18:08

vindyz


People also ask

Can you write a function similar to printf ()?

Similar Functions Other C functions that are similar to the printf function: fprintf function <stdio. h> sprintf function <stdio.

How can printf () and scanf () take multiple arguments?

How can printf () and scanf () take multiple arguments? Each argument takes a size of integer in stack. For data types whose sizes are greater than integer, double or multiples of integer size are taken. Inside the function, we take the pointer of the first argument.

How many arguments must be sent to the printf () function?

C Program 2.1 contains a printf() statement with only one argument, that is, a text string. This string is referred to as the message string and is always the first argument of printf(). It can contain special control characters and/or parameter conversion control characters.

What is the prototype for the printf () function?

The prototype of printf() is: int printf(char *format, arg1, arg2, ...); printf converts, formats, and prints its arguments on the standard output. It returns the number of characters printed.


2 Answers

Here's an excerpt from a past project that I found to work well for me. Some initialization steps are of course missing. The key here is the vfprintf function which will handle the details of printing the various arguments.

void _proxy_log(log_level_t level, const char *fmt, ...)     __attribute__((format (printf, 2, 3)));  #define proxy_log(level, fmt, ...) _proxy_log(level, fmt"\n", ##__VA_ARGS__)  void _proxy_log(log_level_t level, const char *fmt, ...) {     va_list arg;     FILE *log_file = (level == LOG_ERROR) ? err_log : info_log;      /* Check if the message should be logged */     if (level > log_level)         return;      /* Write the error message */     va_start(arg, fmt);     vfprintf(log_file, fmt, arg);     va_end(arg);  #ifdef DEBUG     fflush(log_file);     fsync(fileno(log_file)); #endif } 
like image 174
Michael Mior Avatar answered Sep 20 '22 00:09

Michael Mior


Using "va_arg" http://www.cplusplus.com/reference/clibrary/cstdarg/va_arg/

like image 35
Rodrigo Avatar answered Sep 21 '22 00:09

Rodrigo