Mercurial > hg > toybox
comparison lib/lib.c @ 115:19b5567f0a1b
Add readlink, xreadlink(), and change xrealloc() to not fight the stupid
compiler so much.
author | Rob Landley <rob@landley.net> |
---|---|
date | Sun, 29 Apr 2007 19:55:21 -0400 |
parents | aa4fa2543a65 |
children | ef2bc92d5fb0 |
comparison
equal
deleted
inserted
replaced
114:ce6956dfc0cf | 115:19b5567f0a1b |
---|---|
92 return ret; | 92 return ret; |
93 } | 93 } |
94 | 94 |
95 // Die unless we can change the size of an existing allocation, possibly | 95 // Die unless we can change the size of an existing allocation, possibly |
96 // moving it. (Notice different arguments from libc function.) | 96 // moving it. (Notice different arguments from libc function.) |
97 void xrealloc(void **ptr, size_t size) | 97 void *xrealloc(void *ptr, size_t size) |
98 { | 98 { |
99 *ptr = realloc(*ptr, size); | 99 ptr = realloc(ptr, size); |
100 if (!*ptr) error_exit("xrealloc"); | 100 if (!ptr) error_exit("xrealloc"); |
101 | |
102 return ptr; | |
101 } | 103 } |
102 | 104 |
103 // Die unless we can allocate a copy of this many bytes of string. | 105 // Die unless we can allocate a copy of this many bytes of string. |
104 void *xstrndup(char *s, size_t n) | 106 void *xstrndup(char *s, size_t n) |
105 { | 107 { |
450 } while (bottom + 1 != top); | 452 } while (bottom + 1 != top); |
451 | 453 |
452 return pos + 1; | 454 return pos + 1; |
453 } | 455 } |
454 | 456 |
457 // This can return null (meaning file not found). It just won't return null | |
458 // for memory allocation reasons. | |
459 char *xreadlink(char *name) | |
460 { | |
461 int len, size = 0; | |
462 char *buf = 0; | |
463 | |
464 // Grow by 64 byte chunks until it's big enough. | |
465 for(;;) { | |
466 size +=64; | |
467 buf = xrealloc(buf, size); | |
468 len = readlink(name, buf, size); | |
469 | |
470 if (len<0) { | |
471 free(buf); | |
472 return 0; | |
473 } | |
474 if (len<size) { | |
475 buf[len]=0; | |
476 return buf; | |
477 } | |
478 } | |
479 } | |
480 | |
455 /* | 481 /* |
456 This might be of use or might not. Unknown yet... | 482 This might be of use or might not. Unknown yet... |
457 | 483 |
458 // Read contents of file as a single freshly allocated nul-terminated string. | 484 // Read contents of file as a single freshly allocated nul-terminated string. |
459 char *readfile(char *name) | 485 char *readfile(char *name) |