Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add one generic parameter to printf

Tags:

c

printf

I think it is a wrapper function to printf. For example:

my_printf("Hello world\n")

prints

[1] Hello world

or

[hh:mm:ss] Hello world

I know I see it in Linux kernel but not sure how to implement it in my own application.

In first example above, the number is incremented so the next call to my_printf will be 2. e.g

my_printf("Hello universe\n");

prints

[2] Hello universe

User is never passing generic parameter but still it is printed.

like image 394
Asam Padeh Avatar asked Jun 12 '26 09:06

Asam Padeh


1 Answers

The trick with a static variable was already mentioned.

2nd part of the puzzle is to use things offered in stdarg.h.

The last part of puzzle is vprintf() which can be used for the variable argument list.

A sample:

#include <stdio.h>
#include <stdarg.h>

int my_printf(const char *fmt, ...)
{
  static unsigned counter = 0;
  int len1 = printf("[%d] ", ++counter);
  if (len1 < 0) return len1;
  va_list args;
  va_start(args, fmt);
  int len2 = vprintf(fmt, args);
  va_end(args);
  return len2 < 0 ? len2 : len1 + len2;
}


int main(void)
{
  my_printf("Hello world.\n");
  my_printf("%s", "Hello world, again.\n");
  for (int i = 2; i <= 4; ++i) my_printf("Hello %d. world.\n", i);
}

Output:

[1] Hello world.
[2] Hello world, again.
[3] Hello 2. world.
[4] Hello 3. world.
[5] Hello 4. world.

Live Demo on coliru


If the counter should be an argument instead of a static variable, my_printf() could be adjusted resp.:

#include <stdio.h>
#include <stdarg.h>

int my_printf(unsigned counter, const char *fmt, ...)
{
  int len1 = printf("[%d] ", counter);
  if (len1 < 0) return len1;
  va_list args;
  va_start(args, fmt);
  int len2 = vprintf(fmt, args);
  va_end(args);
  return len2 < 0 ? len2 : len1 + len2;
}

int main(void)
{
  unsigned counter = 0;
  my_printf(++counter, "Hello world.\n");
  my_printf(++counter, "%s", "Hello world, again.\n");
  for (int i = 2; i <= 4; ++i) my_printf(++counter, "Hello %d. world.\n", i);
}

Live Demo on coliru

Incrementing counter in my_printf() wouldn't affect the variable passed as argument. (C is always passing arguments by value.) In that case, the counter had to be passed by pointer instead.

like image 195
Scheff's Cat Avatar answered Jun 15 '26 04:06

Scheff's Cat