All pastes #46423 Raw Edit

Stuff

public text v1 · immutable
#46423 ·published 2006-03-21 01:37 UTC
rendered paste body
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>

/*
 * mprintf, a sprintf clone that automaticly mallocs the string
 * and new content to same string applys after that content.
 */
int mprintf (char ** p, const char *format, ...)
{
    va_list arg; /* used for the variable lists */

    int len = 0;     /* will contain lent for current string */
    int add_len = 0; /* This mutch more strings are we gonna alloc for */
    
    /*printf("\n\nmprintf(%s);\n", format);*/
    
    /* count old chars */
    if(*p)
        len = strlen(*p);

    /*
     * format contains the minimum needed chars that
     * are gonna be used, so we set that value and try
     * with that.
     */
    add_len = strlen(format) + 1;
    
    /*
     * Now realloc the memoryspace containing the
     * string so that the new apending string will
     * have room.
     * Also have a check that it succeds.
     */
    /*printf("Changing size to %i\n", len + add_len);*/
    if(!(*p=realloc(*p, ((len + add_len) * sizeof(char)))))
	return(-1);

    /* Ok, have a try until vsnprintf succeds */
    while(1)
    {
	/* start filling the newly allocaded area */
	va_start (arg, format);
	int done = vsnprintf ((*p)+len, add_len, format, arg);
	va_end (arg);
	
	/* check if that was enouth */
	if(done > -1 && done < add_len)
	{
	    /*printf("GOOD: done : %i, len: %i\n", done, add_len);*/

	    /* Ok return happily */
	    return(done);
	}
	/*printf("BAD: done : %i, len: %i\n", done, add_len);*/

	/* try increase it a bit. */
	add_len = ( done < 0 ? add_len * 2 : done + 1);
	/*printf("Changing size to %i\n", len + add_len);*/
	if(!(*p=realloc(*p, ((len + add_len) * sizeof(char)))))
	    return(-1);
	
    }
    
    /* will never go here */
    return(-1);
}


int main(int argc, char **argv)
{
    char *test=NULL;

    mprintf(&test, "Hello world\n");
    mprintf(&test, "This is a funny test\n");
    mprintf(&test, "Of an self reallocating function\n");
    mprintf(&test, "that shud work with %s\n", "variables");


    printf("This is test (%i): \n\"%s\"\n", strlen(test), test);

    free(test);
    exit(0);
}