C Programming: Forward variable argument list

前端 未结 4 1169
北荒
北荒 2020-11-28 09:32

I\'m trying to write a function that accepts a variable number of parameters like printf, does some stuff, then passes the variable list to printf. I\'m not sure how to do t

4条回答
  •  遥遥无期
    2020-11-28 10:26

    Don't pass the results to printf. pass them to vprintf. vprintf specifically exists to handle passing in va_list arguments. From the Linux man page:

    #include 
    
    int printf(const char *format, ...);
    int fprintf(FILE *stream, const char *format, ...);
    int sprintf(char *str, const char *format, ...);
    int snprintf(char *str, size_t size, const char *format, ...);
    
    #include 
    
    int vprintf(const char *format, va_list ap);
    int vfprintf(FILE *stream, const char *format, va_list ap);
    int vsprintf(char *str, const char *format, va_list ap);
    int vsnprintf(char *str, size_t size, const char *format, va_list ap);
    

    Notice how the latter explicitly take va_list arguments such as the ones you declare inside a function taking ... in the parameter list. So your function would be declared like this:

    void forward_args( const char *format , ... ){
       va_list arglist;
       va_start( arglist, format );
       vprintf( format, arglist );
       va_end( arglist );
    }
    

提交回复
热议问题