mstiles92
mstiles92

Reputation: 31

C - Pass variable number of command line arguments into method with variable number of parameters

I am writing a C program that will take a variable number of command line arguments. I need to then take these arguments and pass them into a function that takes a variable number of filenames as individual parameters (using va_arg to get the arguments inside the function), prototyped as:

void FindFile(char *filename1, ...);

My implementation of FindFile is fine. My question is, how do I take the variable number of arguments in the main method's 'char *argv[]' and use them as parameters when calling FindFile?

This is an assignment for a class, so the FindFile prototype can not be changed. I have searched for ways to make this work, only finding one answer, which said that it is impossible to do. Is this actually the case? It is the exact specification given by my professor so I assumed it would be possible somehow, but the exact method was not discussed in class.

Upvotes: 3

Views: 1459

Answers (2)

luser droog
luser droog

Reputation: 19484

I've done something like this in my postscript interpreter.

This is from my operator-handler function. It uses a switch statement to make the variadic call through the function pointer.

call: /* pass args bottom-up */
    tos = siq; /* pop the stack to the 'stack in question' */
    /* room for output? */
    if (tos-os + op.sig[i].out > OSSIZE) error(st,stackoverflow);
    switch (op.sig[i].n) {
        case 0: op.sig[i].fp(st); break;
        case 1: op.sig[i].fp(st, siq[0]); break;
        case 2: op.sig[i].fp(st, siq[0], siq[1]); break;
        case 3: op.sig[i].fp(st, siq[0], siq[1], siq[2]); break;
        case 4: op.sig[i].fp(st, siq[0], siq[1], siq[2], siq[3]); break;
        case 5: op.sig[i].fp(st, siq[0], siq[1], siq[2], siq[3], siq[4]); break;
        case 6: op.sig[i].fp(st, siq[0], siq[1], siq[2], siq[3], siq[4], siq[5]); break;
        default: error(st,unregistered);
    }

I borrowed this technique from the Goswell interpreter (AKA Rutherford interpreter, AKA RALpage).

Upvotes: 2

What it is not possible to do (at least in K&R, ansi-c and c99 and barring implementation dependent tricks) is to append selected command-line arguments to some kind of argument list at run time and pass that to your function. Too bad, as that's the first thing that comes to mind.

That makes your problem one of figuring out what you can do. You could for instance call (the given varidac function as) FindFile(fname, argc, argv); every single time. It would be silly (really, very, very silly) to write code like that instead of just giving FindFile a fixed signature, but the given varargs version of FindFile could be written to manage that just fine.

If you wanted to pass only some of the command-line arguments you would make a new char*[] containing just the ones you want and pass that in.

Upvotes: 2

Related Questions