Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function arguments like printf in C

Tags:

c

printf

I want to implement a function Myprintf() that takes arguments like printf(). Now I am doing this by:

sprintf(demoString, "Num=%d String=%s", num, str);
Myprintf(demoString);

I want to replace this function call as:

Myprintf("Num=%d String=%s", num, str);

How is this possible?

like image 433
Shihab Avatar asked Feb 08 '13 05:02

Shihab


People also ask

Which function is similar to printf in C?

The printf and its relatives are in a family of functions called variadic functions and there are macros/functions in the <stddef. h> header in the C standard library to manipulate variadic argument lists.

Can you write a function similar to printf ()?

Similar Functionssprintf function <stdio. h> vfprintf function <stdio. h>

What is argument in printf?

The parameters passed into printf() are known as arguments; these are separated commas. 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().

Can you printf a function in C?

1. printf() function in C language: In C programming language, printf() function is used to print the (“character, string, float, integer, octal and hexadecimal values”) onto the output screen. We use printf() function with %d format specifier to display the value of an integer variable.


1 Answers

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

extern int Myprintf(const char *fmt, ...);

int Myprintf(const char *fmt, ...)
{
    char buffer[4096];
    va_list args;
    va_start(args, fmt);
    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
    va_end(args);
    ...print the formatted buffer...
    return rc;
}

It isn't clear from your question exactly how the output is done; your existing Myprintf() presumably outputs it somewhere, maybe with fprintf(). If that's the case, you might write instead:

int Myprintf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    int rc = vfprintf(debug_fp, fmt, args);
    va_end(args);
    return rc;
}

If you don't want to use the return value, declare the function as void and don't bother with the variable rc.

This is a fairly common pattern for 'printf() cover functions'.

like image 160
Jonathan Leffler Avatar answered Oct 15 '22 10:10

Jonathan Leffler