LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   vsprintf and va_list - string length? (https://www.linuxquestions.org/questions/programming-9/vsprintf-and-va_list-string-length-622784/)

Ephracis 02-21-2008 08:39 AM

vsprintf and va_list - string length?
 
Ok, so how to explain this easy?

Well I have a function that takes a char* and a va_list as arguments.
It will then send the complete, processed string to another function.

Example:
Code:

void function(char *txt, va_list args)
{
    /* the char way
      * problem: don't know the length of txt + arguments
      */
    char *string1 = malloc(???);
    vsprintf(string1, txt, args);
    another_function(string1);

    /* the string way
      * problem: don't know how to use it with vsprintf()
      */
    string string2;
    ???
    another_function(string2.c_str());
}

void another_function(char *txt)
{
    printf("I got: %s\n", txt);
}

So, two ways to go:

1) Use char* with malloc. I need to know how long the complete string will be to avoid having to chop it.

2) Use string. But can I use it with a va_list?

Guttorm 02-21-2008 09:19 AM

Hi

I don't think there is a standard C/C++ way of handling this. But GNU has some functions that are not standard, but avaiable in Linux: vasprintf and asprintf. They work like sprintf, but you don't pass a string pointer, but the address of one. The string is then allocated for you, so you don't need to worry about size.

Example:

Code:

#define GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>

void myprintf(const char *format, ...)
{
  char *ptr;
  va_list list;
  va_start(list,format);
  vasprintf(&ptr,format,list);
  printf("Formated: %s\nLength=%d\n", ptr, strlen(ptr));
  free(ptr);
  va_end(list);
}

int main(int argc, const char *argv[])
{
  myprintf("Hello %s", "world");
  return 0;
}

Too bad those functions are not in the C/C++ standard...

cicorino 02-21-2008 10:09 AM

Does the standard vsnprintf with a small size argument (1 for example) return the size minus one required by your malloc? If so it could avoid you to use nonstandard functions, but it could reduce a lot the speed of your code too because of a double call to vsnprintf.


All times are GMT -5. The time now is 07:02 PM.