GRASS Programmer's Manual  6.5.svn(2014)-r66266
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
asprintf.c
Go to the documentation of this file.
1 
28 #define _GNU_SOURCE /* enable asprintf */
29 #include <grass/config.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <unistd.h>
34 #include <assert.h>
35 #include <grass/gis.h>
36 
37 #ifdef __MINGW32__
38 #include <windows.h>
39 #endif /* __MINGW32__ */
40 
41 
42 #ifndef G_asprintf
43 
57 #ifdef HAVE_ASPRINTF
58 
59 int G_vasprintf(char **out, const char *fmt, va_list ap)
60 {
61  return vasprintf(out, fmt, ap);
62 }
63 
64 #else
65 
66 int G_vasprintf(char **out, const char *fmt, va_list ap)
67 {
68  int ret_status = EOF;
69  char dir_name[2001];
70  char file_name[2000];
71  FILE *fp = NULL;
72  char *work = NULL;
73 
74  assert(out != NULL && fmt != NULL);
75 
76  /* Warning: tmpfile() does not work well on Windows (MinGW)
77  * if user does not have write access on the drive where
78  * working dir is? */
79 #ifdef __MINGW32__
80  /* file_name = G_tempfile(); */
81  GetTempPath(2000, dir_name);
82  GetTempFileName(dir_name, "asprintf", 0, file_name);
83  fp = fopen(file_name, "w+");
84 #else
85  fp = tmpfile();
86 #endif /* __MINGW32__ */
87 
88  if (fp) {
89  int count;
90 
91  count = vfprintf(fp, fmt, ap);
92  if (count >= 0) {
93  work = G_calloc(count + 1, sizeof(char));
94  if (work != NULL) {
95  rewind(fp);
96  ret_status = fread(work, sizeof(char), count, fp);
97  if (ret_status != count) {
98  ret_status = EOF;
99  G_free(work);
100  work = NULL;
101  }
102  }
103  }
104  fclose(fp);
105 #ifdef __MINGW32__
106  unlink(file_name);
107 #endif /* __MINGW32__ */
108  }
109  *out = work;
110 
111  return ret_status;
112 }
113 
114 #endif /* HAVE_ASPRINTF */
115 
116 int G_asprintf(char **out, const char *fmt, ...)
117 {
118  va_list ap;
119  int count;
120 
121  va_start(ap, fmt);
122  count = G_vasprintf(out, fmt, ap);
123  va_end(ap);
124 
125  return count;
126 }
127 
128 #endif /* G_asprintf */
void G_free(void *buf)
Free allocated memory.
Definition: gis/alloc.c:142
int count
int G_asprintf(char **out, const char *fmt,...)
Definition: asprintf.c:116
char * file_name
return NULL
Definition: dbfopen.c:1394
fclose(fd)
int G_vasprintf(char **out, const char *fmt, va_list ap)
Safe replacement for asprintf().
Definition: asprintf.c:66