I want to define a function in C language which can take an unlimited number of arguments of any datatype.
For example: printf(), scanf(), etc.
Any idea on this?
Declare the function as taking a ... last argument. You'll need to use the macros from <stdarg.h> to access the arguments as a va_list.
If you just want something "like printf, but with a little extra behavior", then you can pass the va_list to vprintf, vfprintf, or vsprintf.
#include <stdarg.h>
#include <stdio.h>
#include <time.h>
#ifdef __GNUC__
__attribute__((format(printf, 1, 2)))
#endif
void PrintErrorMsg(const char* fmt, ...)
{
time_t now;
char buffer[20];
va_list args;
va_start(args, fmt);
time(&now);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", gmtime(&now));
fprintf(stderr, "[%s] ", buffer);
vfprintf(stderr, fmt, args);
fputc('\n', stderr);
va_end(args);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With