Releasing version 3-2014010505
[notion/jeffpc.git] / libtu / misc.c
blob39137c3bb1514546b51258415b8e01d8aee88598
1 /*
2 * libtu/misc.c
4 * Copyright (c) Tuomo Valkonen 1999-2002.
6 * You may distribute and modify this library under the terms of either
7 * the Clarified Artistic License or the GNU LGPL, version 2.1 or later.
8 */
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <ctype.h>
15 #include "misc.h"
16 #include "output.h"
19 void *malloczero(size_t size)
21 void *p=malloc(size);
23 if(p!=NULL)
24 memset(p, 0, size);
25 else
26 warn_err();
28 return p;
32 void *remalloczero(void *ptr, size_t oldsize, size_t newsize)
34 void *p=NULL;
36 if(newsize!=0){
37 p=realloc(ptr, newsize);
39 if(p==NULL){
40 warn_err();
41 return NULL;
44 if(newsize>oldsize)
45 memset((char*)p+oldsize, 0, newsize-oldsize);
48 return p;
52 char *scopyn(const char *p, size_t l)
54 char *pn=ALLOC_N(char, l+1);
56 if(pn==NULL)
57 return NULL;
59 memcpy(pn, p, l);
60 pn[l]='\0';
62 return pn;
66 char *scopy(const char *p)
68 size_t l=strlen(p);
69 return scopyn(p, l);
73 char *scat(const char *p1, const char *p2)
75 size_t l1, l2;
76 char*pn;
78 l1=strlen(p1);
79 l2=strlen(p2);
81 pn=ALLOC_N(char, l1+l2+1);
83 if(pn==NULL)
84 return NULL;
86 memcpy(pn, p1, l1);
87 memcpy(pn+l1, p2, l2+1);
89 return pn;
93 char *scat3(const char *p1, const char *p2, const char *p3)
95 size_t l1, l2, l3;
96 char *pn;
98 l1=strlen(p1);
99 l2=strlen(p2);
100 l3=strlen(p3);
102 pn=ALLOC_N(char, l1+l2+l3+1);
104 if(pn==NULL)
105 return NULL;
107 memcpy(pn, p1, l1);
108 memcpy(pn+l1, p2, l2);
109 memcpy(pn+l1+l2, p3, l3+1);
111 return pn;
115 char *scatn(const char *s1, ssize_t l1, const char *s2, ssize_t l2)
117 size_t tlen=1;
118 char *s;
120 if(l1<0)
121 l1=strlen(s1);
123 if(l2<0)
124 l2=strlen(s2);
126 tlen+=l1+l2;
128 s=ALLOC_N(char, tlen);
130 if(s==NULL)
131 return NULL;
133 memcpy(s, s1, l1);
134 memcpy(s+l1, s2, l2);
135 s[l1+l2]='\0';
137 return s;
141 /* */
144 const char *simple_basename(const char *name)
146 const char *p;
148 p=name+strlen(name)-1;
150 /* Skip any trailing slashes */
151 while(*p=='/'){
152 /* root? */
153 if(p==name)
154 return name;
155 p--;
158 while(p!=name){
159 if(*p=='/')
160 return p+1;
161 p--;
164 return name;
168 void stripws(char *p)
170 int l;
172 l=strspn(p, " ");
173 if(l!=0)
174 strcpy(p, p+l);
175 l=strlen(p);
177 while(--l>=0){
178 if(*(p+l)!=' ')
179 break;
181 *(p+l+1)='\0';
185 const char *libtu_strcasestr(const char *str, const char *ptn)
187 const char *s2, *p2;
188 for(; *str; str++) {
189 for(s2=str, p2=ptn; ; s2++, p2++) {
190 if(!*p2)
191 return str;
192 if(toupper(*s2)!=toupper(*p2))
193 break;
196 return NULL;
199 /* */
202 bool readf(FILE *f, void *buf, size_t n)
204 return fread(buf, 1, n, f)!=1;
208 bool writef(FILE *f, const void *buf, size_t n)
210 return fwrite(buf, 1, n, f)!=1;