home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!munnari.oz.au!bruce.cs.monash.edu.au!monu6!escargot!goanna!ok
- From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe)
- Newsgroups: comp.lang.c
- Subject: Re: definition of strncpy stupid?
- Message-ID: <16225@goanna.cs.rmit.oz.au>
- Date: 15 Dec 92 03:18:27 GMT
- References: <1992Dec8.181543.15339@dnbf01.bram.cdx.mot.com> <1992Dec9.191804.3455@rti.rti.org>
- Organization: Comp Sci, RMIT, Melbourne, Australia
- Lines: 61
-
- In article <1992Dec9.191804.3455@rti.rti.org>, jbs@rti.rti.org writes:
- > Look, the whole point of the complaint is that it's *inconvenient* to have
- > to write code to add a null to the target of strncpy() after 9 out of 10
- > calls to it
-
- If you find yourself doing that, the answer is that you are abusing strncpy.
- If you want a substring function, write one. strncpy is not and never has
- been that function. memcpy() is the appropriate library function to start
- from.
-
- > Most of us have. It's just that it seems really odd that every
- > other package I've seen that deals with strings has a substr() function
- > that copies N characters from the source to the target, and the result is a
- > string that you can use in all the rest of the string functions. Why
- > doesn't C have one?
-
- It has. It's called sprintf(). The equivalent of
- (string-append
- "foo"
- (substring Bar 2 3)
- "ugh"
- (substring Zap 1 4)
- "ooy")
- in C would be
- sprintf(result, "foo%.*sugh%.*sooy", 3-2, Bar+2, 4-1, Zap+1);
-
- If you can't stand that, try
-
- /* substr.h */
- #include <stddef.h>
- extern char *substr(char *, const char *, size_t, size_t);
-
- /* substr.c */
-
- #include <assert.h>
- #include <string.h>
- #include <substr.h>
-
- char *substr(char *dst, const char *src, size_t offset, size_t length)
- {
- assert(offset + length <= strlen(src));
- memcpy(dst, src+offset, length);
- dst[length] = '\0';
- return dst;
- }
-
- /* A different approach would say that we want
- length .TAKE offset .DROP src. For that we'd write
- */
- char *substr(char *dst, const char *src, size_t offset, size_t length)
- {
- size_t srclen = strlen(src);
-
- if (offset > srclen) offset = srclen;
- if (length > srclen-offset) length = srclen-offset;
- memcpy(dst, src+offset, length);
- dst[length] = '\0';
- return dst;
- }
-
- /* End of substr.h */
-