1 |
#include <stdio.h> |
2 |
#include <ctype.h> |
3 |
#include <string.h> |
4 |
|
5 |
|
6 |
/* |
7 |
* An implementation of strstr() with case-insensitivity. |
8 |
*/ |
9 |
char *strcasestr(const char *haystack, const char *needle) |
10 |
{ |
11 |
char *h, *n, *c; |
12 |
size_t hl, nl; |
13 |
|
14 |
c = (char *)haystack; |
15 |
n = (char *)needle; |
16 |
hl = strlen(haystack); |
17 |
nl = strlen(needle); |
18 |
|
19 |
while (hl >= nl) { |
20 |
while (tolower(*c) != tolower(*needle)) { |
21 |
c++; |
22 |
hl--; |
23 |
if (hl < nl) |
24 |
return NULL; |
25 |
} |
26 |
|
27 |
h = c; |
28 |
n = (char *)needle; |
29 |
|
30 |
while (tolower(*h) == tolower(*n)) { |
31 |
h++; |
32 |
n++; |
33 |
|
34 |
if (!*n) |
35 |
return c; |
36 |
} |
37 |
c++; |
38 |
hl--; |
39 |
} |
40 |
|
41 |
return NULL; |
42 |
} |
43 |
|
44 |
|
45 |
/* |
46 |
* Convert an unsigned long integer to a string. |
47 |
*/ |
48 |
char *ultostr(unsigned long int num, int base) |
49 |
{ |
50 |
unsigned int d; |
51 |
static char s[65]; |
52 |
char *c; |
53 |
|
54 |
if (base < 2 || base > 36) |
55 |
return NULL; |
56 |
|
57 |
c = s + 64; |
58 |
*c = 0; |
59 |
|
60 |
do { |
61 |
d = num % base; |
62 |
num /= base; |
63 |
|
64 |
if (d <= 9) |
65 |
*--c = '0' + d; |
66 |
else |
67 |
*--c = 'a' + d - 10; |
68 |
} while (c >= s && num); |
69 |
|
70 |
return c; |
71 |
} |
72 |
|
73 |
|
74 |
/* |
75 |
* Copies at most size characters from the string pointed by src to the |
76 |
* array pointed by dest, always NULL terminating (unless size == 0). |
77 |
* Returns pointer to dest. |
78 |
*/ |
79 |
char *xstrncpy(char *dest, const char *src, size_t size) |
80 |
{ |
81 |
char *d = dest; |
82 |
const char *s = src; |
83 |
size_t n = size; |
84 |
|
85 |
while (n) { |
86 |
if (!(*d++ = *s++)) |
87 |
break; |
88 |
n--; |
89 |
} |
90 |
|
91 |
if (!n && size) |
92 |
*d = 0; |
93 |
|
94 |
return dest; |
95 |
} |