Variable Argument List Passing

This is a discussion on Variable Argument List Passing within the C++ Programming forums, part of the General Programming Boards category; So I'm abusing C++ in strange and wonderful ways, and I want to write a function like this: Code: void ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    28

    Question Variable Argument List Passing

    So I'm abusing C++ in strange and wonderful ways, and I want to write a function like this:
    Code:
    void Log(char *filename, char *str, ...);
    This function would open a file specified by filename and then call printf in the following sort of fashion:
    Code:
    fprintf(fp,str, ...);
    The idea is to create a function that loads up a log file, printf's the stuff from str and ... to the log, and closes it, all nice and tidy. For example, you could do:
    Code:
    int a = 20;
    Log("flarp.txt", "%d", a);
    and "20" would end up in flarp.txt. Trouble is, I can't figure out how to take the variable number of args passed to the Log function and then pass those arguments from Log to printf. I tried the following, expecting that it wouldn't work:
    Code:
    #include <stdio.h>
    #include <stdarg.h>
    
    void printme(char * str, ...) {
        va_list arglist;
        va_start(arglist, str);
        printf(str, arglist);
        va_end(arglist);
    };
    
    int main () {
        int a = 20;
        printme("%d",a);
        getchar();
        return 0;
    };
    And the result was some random number, which I suspect was the address of the first argument in the "..." in "printme()". (EDIT: it is the value of "arglist", which I expect is a pointer). So, help, please?
    Last edited by Orborde; 05-10-2005 at 07:08 PM. Reason: More info added, typo corrected

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    62
    Function vfprintf() is the key.

    Code:
    vfprintf(stdout, str, arglist);
    Instead of stdout, you may want to use any other (valid) file handle.

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    28
    Yoink. You're a genius. Thanks a bunch.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help sorting a linked list. Beginner
    By scarlet00014 in forum C Programming
    Replies: 1
    Last Post: 09-27-2008, 06:16 PM
  2. intercepting functions with a variable argument list
    By Peter_Machner in forum C++ Programming
    Replies: 2
    Last Post: 10-10-2005, 06:25 AM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 09:33 PM
  4. compiler build error
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2003, 09:16 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21