length of va_list when using variable list arguments?

后端 未结 6 442
花落未央
花落未央 2020-12-14 15:23

Is there any way to compute length of va_list? All examples I saw the number of variable parameters is given explicitly.

6条回答
  •  一生所求
    2020-12-14 15:42

    You can try to use function _vscprintf if you work under MS Visual Studio. Here is an example how to use _vscprintf, I used it to know how much space I require to malloc for my console title.

    int SetTitle(const char *format,...){
        char *string;
        va_list arguments;
    
        va_start(arguments,format);
            string=(char *)malloc(sizeof(char)*(_vscprintf(format,arguments)+1));
            if(string==NULL)
                SetConsoleTitle("Untitled");
            else
                vsprintf(string,format,arguments);
        va_end(arguments);
    
        if(string==NULL)
            return SETTITLE_MALLOCFAILED;
        SetConsoleTitle(string);
        free(string);
        return 0;
    }
    

    Or you can do this, add output to temporary file and then read data from it to allocated memory like I did in this next example:

    void r_text(const char *format, ...){
        FILE *tmp = tmpfile();
        va_list vl;
        int len;
        char *str;
    
        va_start(vl, format);
            len = vfprintf(tmp, format, vl);
        va_end(vl);
        rewind(tmp);
        str = (char *) malloc(sizeof(char) * len +1);
        fgets(str, len+1, tmp);
        printf("%s",str);
        free(str);
        fclose(tmp);
    }
    

提交回复
热议问题