hudac
hudac

Reputation: 2798

Is it possible to use va_list method twice in a function?

I want to use the va_list method twice, in one function. can I do that?

#include <cstdarg>

void printFDS(int num_fds, ... , const char *fmt, ...) {

    va_list fds, args;
    va_start(fds, num_fds);
    va_start(args, fmt);

    for (int i = 0; i < num_fds; i++) {
        vsprintf(va_arg(fds, FILE*), fmt, args);
    }
    va_end(args);
    va_end(fds);
}

So I'll be able to call that function like that:

printFDS(1, stderr, "Error: %s\n", stderror(errno));

or printFDS(2, stderr, otherFD, "Error: %s\n", stderror(errno));

while FILE *otherFD = fopen ("somefile", "w");

My purpose: to print information, on a list of fd's..

Thanks

Upvotes: 2

Views: 952

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409404

That's not possible, the ellipsis (the three dots) must be only once and only last.


If you have a C++11 capable compiler, you might be able to do it with an initializer list and std::vector for the first argument:

void printFDS(const std::vector<FILE*>& files, const char* fmt, ...)
{
    // ...
}

You could cal it as

printFDS({ stderr, otherFilePointer }, "Error: %s\n", std::strerror(errno));

Upvotes: 5

user743382
user743382

Reputation:

You cannot do this directly. What you can do, though, is

void printFDS(int num_fds, ...)

and in your function, use va_copy to get two va_list variables. In one, read the FILE *s. In the other, first skip num_fds FILE *s, then use va_arg to get the format string.

You will need to do some more copying to ensure that that second va_list isn't trashed by vfprintf, you can again use va_copy for that.

Upvotes: 4

Related Questions