CPN
Computational Process Networks
ToString.cc
Go to the documentation of this file.
1 //=============================================================================
2 // Computational Process Networks class library
3 // Copyright (C) 1997-2006 Gregory E. Allen and The University of Texas
4 //
5 // This library is free software; you can redistribute it and/or modify it
6 // under the terms of the GNU Library General Public License as published
7 // by the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Library General Public License for more details.
14 //
15 // The GNU Public License is available in the file LICENSE, or you
16 // can write to the Free Software Foundation, Inc., 59 Temple Place -
17 // Suite 330, Boston, MA 02111-1307, USA, or you can find it on the
18 // World Wide Web at http://www.fsf.org.
19 //=============================================================================
23 #include "common_priv.h"
24 #include <cpn/utils/ToString.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdarg.h>
28 
29 // This code was taken from an example of how
30 // to use vsnprintf in the unix man pages.
31 std::string ToString(const char *fmt, ...)
32 {
33  /* Guess we need no more than 100 bytes. */
34  int n, size = 100;
35  char *p, *np;
36  va_list ap;
37  std::string ret = "";
38  p = (char*)malloc(size);
39  if (p == NULL) {
40  return ret;
41  }
42 
43  while (1) {
44  /* Try to print in the allocated space. */
45  va_start(ap, fmt);
46  n = vsnprintf(p, size, fmt, ap);
47  va_end(ap);
48  /* If that worked, return the string. */
49  if (n > -1 && n < size) {
50  ret = p;
51  free(p);
52  return ret;
53  }
54  /* Else try again with more space. */
55  if (n > -1) {
56  /* glibc 2.1 */
57  size = n+1; /* precisely what is needed */
58  }
59  else { /* glibc 2.0 */
60  size *= 2; /* twice the old size */
61  }
62  np = (char*)realloc (p, size);
63  if (np == NULL) {
64  free(p);
65  return ret;
66  } else {
67  p = np;
68  }
69  }
70 }
71 
std::string ToString(const char *fmt,...)
Definition: ToString.cc:31
A general ToStream function that takes printf like arguments and returns a std::string.