xmalloc string functions
- From: "Malcolm McLean" <regniztar@xxxxxxxxxxxxxx>
- Date: Sun, 27 Jan 2008 14:57:02 -0000
Here are six functions implemented on top of xmalloc(). No C programmer should have any triouble providing the implemetations, though replace and getquote are non-trivial.
char *dup(const char *str);
char *cat(const char *str1, const char *str2);
char *catandkill(char *str1, const char *str2);
char *tok(const char *str, const char *delims, char **end);
char *midstr(const char *str, int idx, int len);
char *replace(const char *str, const char *pattern, const char *rep);
char *getquote(const char *str, char quote, char escape, char **end);
char *getline(FILE *fp);
All return strings allocated with xmalloc().
dup() is strdup(), and duplicates a string. cat() concatenates two strings. catandkill concatenagtes two strings, and frees the first. It also returns dup(str2) is the first pointer is null. It is designed for building strings in conveneint loops.
tok() is strtok() that takes a string argument instead of using a global. midstr() takes out a central portion of the string. replace() is a find and replace, getquote() retrives the next quoted string, allowing for the quotes themselves to be escaped. You will have to escape non-quote escaped characters manually, of course. getline() will be a familiar friend.
I've think we've got something quite powerful here, purely because none of these functions can ever return null for out of memory conditions. It massively simplifies string handling.
The library is not terribly efficient and doesn't pretend to be. If you are doing heavy string processing you might want to look at Paul Hsieh's better string library, that stores a length parameter with strings. It is meant to be a few simple functions for easy manipulation.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
.
- Follow-Ups:
- Re: xmalloc string functions
- From: Paul Hsieh
- Re: xmalloc string functions
- From: Yevgen Muntyan
- Re: xmalloc string functions
- From: Eric Sosman
- Re: xmalloc string functions
- From: santosh
- Re: xmalloc string functions
- Prev by Date: Re: Is Chris Hills a troll?
- Next by Date: Re: Is Chris Hills a troll?
- Previous by thread: Storing data structure
- Next by thread: Re: xmalloc string functions
- Index(es):
Relevant Pages
|