str.c (1043B)
1 /* str.c - helpers de texto sin stdio. */ 2 #include "str.h" 3 4 int str_put(char *buf, int n, int pos, const char *s) 5 { 6 if (pos < 0) return -1; 7 while (*s) { 8 if (pos >= n - 1) return -1; 9 buf[pos++] = *s++; 10 } 11 buf[pos] = 0; 12 return pos; 13 } 14 15 int str_int(char *buf, int n, int pos, long v) 16 { 17 char tmp[24]; 18 int k = 0; 19 unsigned long u = v < 0 ? (unsigned long)(-v) : (unsigned long)v; 20 do { tmp[k++] = (char)('0' + u % 10); u /= 10; } while (u); 21 if (v < 0) tmp[k++] = '-'; 22 if (pos < 0) return -1; 23 while (k) { 24 if (pos >= n - 1) return -1; 25 buf[pos++] = tmp[--k]; 26 } 27 buf[pos] = 0; 28 return pos; 29 } 30 31 const char *str_scan_int(const char *s, long *out) 32 { 33 while (*s == ' ' || *s == '\t') s++; 34 int neg = 0; 35 if (*s == '-') { neg = 1; s++; } 36 if (*s < '0' || *s > '9') return 0; 37 long v = 0; 38 while (*s >= '0' && *s <= '9') { 39 v = v * 10 + (*s - '0'); 40 if (v > 1000000000L) return 0; 41 s++; 42 } 43 *out = neg ? -v : v; 44 return s; 45 }