asprintf.c

Go to the documentation of this file.
00001 #include <stdio.h>
00002 #include <stdlib.h>
00003 #include <stdarg.h>
00004 #include <assert.h>
00005 #include "gis.h"
00006 
00007 /*
00008  * Eric G. Miller egm2@jps.net 
00009  * Thu, 2 May 2002 17:51:54 -0700 
00010  * 
00011  * 
00012  * I've got a sort of cheat for asprintf. We can't use vsnprintf for the
00013  * same reason we can't use snprintf ;-)  Comments welcome (I'm not too
00014  * sure tmpfile() is safe.  It's apparently an anonymous file on my
00015  * machine, as nothing shows up in /tmp or the current directory...)
00016  */
00017 
00018 /* Make sure the macro doesn't impact our function, if it is defined */
00019 #undef G_asprintf
00020 
00021 /* We cheat by printing to a tempfile via vfprintf and then reading it
00022  *  * back in.  Not the most efficient way, probably and tmpfile() is
00023  *  * not safe?
00024  *  */
00025 int
00026   G_asprintf (char **out, const char *fmt, ...)
00027 {
00028        va_list ap;
00029        int ret_status = EOF;
00030        int count = 0;
00031        FILE *fp = NULL;
00032        char *work = NULL;
00033        
00034        assert (out != NULL && fmt != NULL);
00035        
00036        va_start (ap, fmt);
00037        if ((fp = tmpfile()))
00038      {
00039                 count = vfprintf (fp, fmt, ap);
00040                 if (count >= 0)
00041           {
00042                          work = calloc (count + 1, 1);
00043                          if (work != NULL)
00044                {
00045                                   rewind (fp);
00046                                   ret_status = fread (work, 1, count, fp);
00047                                   if (ret_status != count)
00048                     {
00049                                            ret_status = EOF;
00050                                            free (work);
00051                                            work = NULL;
00052                     }
00053                }
00054           }
00055                 fclose (fp);
00056      }
00057        va_end (ap);
00058        *out = work;
00059        return ret_status;
00060 }

Generated on Mon Jan 1 19:49:25 2007 for GRASS by  doxygen 1.5.1