home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / c / 18367 < prev    next >
Encoding:
Text File  |  1992-12-15  |  2.2 KB  |  72 lines

  1. Path: sparky!uunet!munnari.oz.au!bruce.cs.monash.edu.au!monu6!escargot!goanna!ok
  2. From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: definition of strncpy stupid?
  5. Message-ID: <16225@goanna.cs.rmit.oz.au>
  6. Date: 15 Dec 92 03:18:27 GMT
  7. References: <1992Dec8.181543.15339@dnbf01.bram.cdx.mot.com> <1992Dec9.191804.3455@rti.rti.org>
  8. Organization: Comp Sci, RMIT, Melbourne, Australia
  9. Lines: 61
  10.  
  11. In article <1992Dec9.191804.3455@rti.rti.org>, jbs@rti.rti.org writes:
  12. > Look, the whole point of the complaint is that it's *inconvenient* to have
  13. > to write code to add a null to the target of strncpy() after 9 out of 10
  14. > calls to it
  15.  
  16. If you find yourself doing that, the answer is that you are abusing strncpy.
  17. If you want a substring function, write one.  strncpy is not and never has
  18. been that function.  memcpy() is the appropriate library function to start
  19. from.
  20.  
  21. > Most of us have. It's just that it seems really odd that every
  22. > other package I've seen that deals with strings has a substr() function
  23. > that copies N characters from the source to the target, and the result is a
  24. > string that you can use in all the rest of the string functions.  Why
  25. > doesn't C have one?
  26.  
  27. It has.  It's called sprintf().  The equivalent of
  28.     (string-append
  29.         "foo"
  30.         (substring Bar 2 3)
  31.         "ugh"
  32.         (substring Zap 1 4)
  33.         "ooy")
  34. in C would be
  35.     sprintf(result, "foo%.*sugh%.*sooy", 3-2, Bar+2, 4-1, Zap+1);
  36.  
  37. If you can't stand that,  try
  38.  
  39. /* substr.h */
  40. #include <stddef.h>
  41. extern char *substr(char *, const char *, size_t, size_t);
  42.  
  43. /* substr.c */
  44.  
  45. #include <assert.h>
  46. #include <string.h>
  47. #include <substr.h>
  48.  
  49. char *substr(char *dst, const char *src, size_t offset, size_t length)
  50.     {
  51.     assert(offset + length <= strlen(src));
  52.     memcpy(dst, src+offset, length);
  53.     dst[length] = '\0';
  54.     return dst;
  55.     }
  56.  
  57. /*  A different approach would say that we want
  58.     length .TAKE offset .DROP src.  For that we'd write
  59. */
  60. char *substr(char *dst, const char *src, size_t offset, size_t length)
  61.     {
  62.     size_t srclen = strlen(src);
  63.  
  64.     if (offset > srclen) offset = srclen;
  65.     if (length > srclen-offset) length = srclen-offset;
  66.     memcpy(dst, src+offset, length);
  67.     dst[length] = '\0';
  68.     return dst;
  69.     }
  70.  
  71. /* End of substr.h */
  72.