From: Peep P. <so...@us...> - 2004-08-03 14:47:39
|
Update of /cvsroot/agd/client In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv947 Added Files: sys.c sys.h Log Message: Various utility functions. --- NEW FILE: sys.h --- #ifndef _SYS_H #define _SYS_H #define VERSION "v1.0*10-42" #define NET_DEFAULT_PORT 6868 void *xmalloc(size_t bytes); void *xrealloc(void *ptr, size_t bytes); char *xstrdup(char *s); int count_lines(char *s); typedef struct { char *host; int port; } conf_t; extern conf_t conf; typedef struct { char **str; int num; } exploded_t; exploded_t *explode(char *str, char *delim); #endif --- NEW FILE: sys.c --- #include <stdlib.h> #include "sys.h" conf_t conf; void *xmalloc(size_t bytes) { void *ptr; ptr = malloc(bytes); if(!ptr) { printf("Out of memory!\n"); exit(1); } return ptr; } void *xrealloc(void *ptr, size_t bytes) { void *new_ptr; new_ptr = realloc(ptr, bytes); if(!new_ptr) { printf("Out of memory!\n"); exit(1); } return new_ptr; } char *xstrdup(char *s) { char *p; p = xmalloc(strlen(s) + 1); return strcpy(p, s); } int count_lines(char *str) { int i, num; i = 0; if(str[0] && str[0] != '\n') num = 1; while(1) { if(str[i] == '\0') { if(str[i-1] != '\n') num++; break; } if(str[i++] == '\n') num++; } return num; } exploded_t *explode(char *str, char *delim) { char *bgn, *end; exploded_t *ret; int len; ret = xmalloc(sizeof(exploded_t)); ret->str = NULL; ret->num = 0; bgn = str; while(1) { if(!bgn) break; end = strstr(bgn, delim); if(end) len = end - bgn; else len = strlen(bgn); ret->num++; ret->str = xrealloc(ret->str, ret->num * sizeof(char*)); ret->str[ret->num-1] = xmalloc(len + 1); strncpy(ret->str[ret->num-1], bgn, len); ret->str[ret->num-1][len] = '\0'; if(!end) break; bgn = end + 1; } return ret; } |