• Main Page
  • Related Pages
  • Data Structures
  • Files
  • File List
  • Globals

asprintf.c

Go to the documentation of this file.
00001 
00028 #define _GNU_SOURCE             /* enable asprintf */
00029 #include <grass/config.h>
00030 #include <stdio.h>
00031 #include <stdlib.h>
00032 #include <stdarg.h>
00033 #include <unistd.h>
00034 #include <assert.h>
00035 #include <grass/gis.h>
00036 
00037 #ifdef __MINGW32__
00038 #include <windows.h>
00039 #endif /* __MINGW32__ */
00040 
00041 
00042 #ifndef G_asprintf
00043 
00057 #ifdef HAVE_ASPRINTF
00058 
00059 int G_vasprintf(char **out, const char *fmt, va_list ap)
00060 {
00061     return vasprintf(out, fmt, ap);
00062 }
00063 
00064 #else
00065 
00066 int G_vasprintf(char **out, const char *fmt, va_list ap)
00067 {
00068     int ret_status = EOF;
00069     char dir_name[2001];
00070     char file_name[2000];
00071     FILE *fp = NULL;
00072     char *work = NULL;
00073 
00074     assert(out != NULL && fmt != NULL);
00075 
00076     /* Warning: tmpfile() does not work well on Windows (MinGW)
00077      *          if user does not have write access on the drive where 
00078      *          working dir is? */
00079 #ifdef __MINGW32__
00080     /* file_name = G_tempfile(); */
00081     GetTempPath(2000, dir_name);
00082     GetTempFileName(dir_name, "asprintf", 0, file_name);
00083     fp = fopen(file_name, "w+");
00084 #else
00085     fp = tmpfile();
00086 #endif /* __MINGW32__ */
00087 
00088     if (fp) {
00089         int count;
00090 
00091         count = vfprintf(fp, fmt, ap);
00092         if (count >= 0) {
00093             work = G_calloc(count + 1, sizeof(char));
00094             if (work != NULL) {
00095                 rewind(fp);
00096                 ret_status = fread(work, sizeof(char), count, fp);
00097                 if (ret_status != count) {
00098                     ret_status = EOF;
00099                     G_free(work);
00100                     work = NULL;
00101                 }
00102             }
00103         }
00104         fclose(fp);
00105 #ifdef __MINGW32__
00106         unlink(file_name);
00107 #endif /* __MINGW32__ */
00108     }
00109     *out = work;
00110 
00111     return ret_status;
00112 }
00113 
00114 #endif /* HAVE_ASPRINTF */
00115 
00116 int G_asprintf(char **out, const char *fmt, ...)
00117 {
00118     va_list ap;
00119     int count;
00120 
00121     va_start(ap, fmt);
00122     count = G_vasprintf(out, fmt, ap);
00123     va_end(ap);
00124 
00125     return count;
00126 }
00127 
00128 #endif /* G_asprintf */

Generated on Thu Dec 9 2010 20:46:04 for GRASS Programmer's Manual by  doxygen 1.7.2