| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 
 |  
/* basic toolkit
*/
 
// === code ===================================================================
 
#include "toolkit.h"
#include <stdarg.h>
 
/* types for count/size & position/index
   Nat is unsigned to allow for negative index à la Python,
   and for tricks such as 'not-found' = -1
*/
typedef unsigned int Uint ;
typedef int Nat ;
 
/* common output funcs
*/
void line (void) {
   putchar (EOL) ;
}
void write (char * str) {
   printf ("%s", str) ;
}
void end_test () {
   puts ("=================================================================") ;
   line() ;
}
 
/* string funcs
   * format: sprintf returning a new string
     see also:
      int asprintf  (char **strp, const char *fmt, ...) ;
      int vasprintf (char **strp, const char *fmt, va_list ap) ;
*/
char * format (char * form, ...) {
   va_list args ; va_start (args, form) ;
   char *s, *s0 ;
   Uint weight ;
 
   // Determine weight (count of bytes) in output (NUL excluded):
   s0 = malloc (1 * sizeof(char)) ;
   assert (s0 != NULL) ;
   weight = vsnprintf (s0, 1, form, args) ;
   printf ("weight:%i\n", weight) ;
   assert (weight > 0) ;
   weight ++ ;                                  // for NUL terminator
   free (s0) ; s0 = NULL ;
 
   // Write into new string of that weight:
   s = malloc (weight * sizeof(char)) ;
   assert (s != NULL) ;
   weight = vsprintf (s, form, args) ;
//~    printf ("weight:%i\n", weight) ;
 
   va_end (args) ;
   return s ;
}
 
/* debug tool func
*/
int stop (void) { exit (EXIT_SUCCESS) ;}
 
 
 
// === test ===================================================================
void test () {
   char * s = format ("int:%05i float:%+9.3f string:'%9s'",
      123, 1.23, "123") ;
   puts (s) ;
}
int main (void) {
   test () ;
   return EXIT_SUCCESS ;
} | 
Partager