N
Navaneeth
I am writing a dynamically growing string buffer. The following struct
represents a string buffer.
struct strbuf {
char *buffer; /* null terminated buffer */
size_t length; /* length of the string excluding null
terminator */
size_t allocated; /* total memory allocated */
};
I have also got several functions to operate on this. The following
function takes a format and formats it using "vsnprintf" and adds to
the buffer.
int strbuf_addf(struct strbuf *string, const char *format, ...)
{
size_t space_available;
int length;
va_list args;
if(string == NULL) return 0;
space_available = get_available_space(string);
for(;
{
va_start(args, format);
length = vsnprintf(string->buffer + string->length,
space_available, format, args);
va_end(args);
if(length < space_available) break;
grow_buffer(string);
space_available = get_available_space(string);
}
string->length += length;
/* buffer should always contain some free space */
assert(string->length < string->allocated);
return 1;
}
This works well. Now I have a requirement where I would like to call
the above function from another function that takes variable
arguments. Prototype would be,
void print_info(const char *format, ...);
How can I call "strbuf_addf" from "print_info"?
The only way which I can think is add another method to the string
buffer which takes a "va_list". So from "print_info" & "strbuf_addf" I
can get a "va_list" and pass that. Wondering is this the correct
approach?
Any help would be great!
represents a string buffer.
struct strbuf {
char *buffer; /* null terminated buffer */
size_t length; /* length of the string excluding null
terminator */
size_t allocated; /* total memory allocated */
};
I have also got several functions to operate on this. The following
function takes a format and formats it using "vsnprintf" and adds to
the buffer.
int strbuf_addf(struct strbuf *string, const char *format, ...)
{
size_t space_available;
int length;
va_list args;
if(string == NULL) return 0;
space_available = get_available_space(string);
for(;
{
va_start(args, format);
length = vsnprintf(string->buffer + string->length,
space_available, format, args);
va_end(args);
if(length < space_available) break;
grow_buffer(string);
space_available = get_available_space(string);
}
string->length += length;
/* buffer should always contain some free space */
assert(string->length < string->allocated);
return 1;
}
This works well. Now I have a requirement where I would like to call
the above function from another function that takes variable
arguments. Prototype would be,
void print_info(const char *format, ...);
How can I call "strbuf_addf" from "print_info"?
The only way which I can think is add another method to the string
buffer which takes a "va_list". So from "print_info" & "strbuf_addf" I
can get a "va_list" and pass that. Wondering is this the correct
approach?
Any help would be great!