Newsgroups: comp.lang.c Path: utzoo!sq!msb From: msb@sq.sq.com (Mark Brader) Subject: Re: strncpy Message-ID: <1990Jan8.064532.25806@sq.sq.com> Summary: sprintf Reply-To: msb@sq.com (Mark Brader) Organization: SoftQuad Inc., Toronto References: <11527@csli.Stanford.EDU> <000003Q@cdis-1.UUCP> <11616@csli.Stanford.EDU> Date: Mon, 8 Jan 90 06:45:32 GMT > strncpy is a function evidently designed for use with > fixed-length character buffers, not the null-terminated strings that > are semi-standard in C. That makes one wonder why strncpy is included > with functions that are intended for use with null-terminated strings, > and why there is no "safe" copying function for the latter. The first question has, in effect, already been answered: the behavior of strncpy() was that required for writing entries in UNIX directories. It was natural to put it in the library so that programs could use it for other purposes, and once it became common for them to do so, it had to remain there forever for compatibility. (One example of an "other purpose", by the way, is strncpy(dest, "", n), which puts all zero bits in the destination without needing an ifdef to choose bzero() or memset(). I make no claim that it's fast or readable, but it's certainly legitimate.) As to the second question, there IS a simple way to get the effect of if (strlen (src) > n) { strncpy(dest, src, n); dest[n] = '\0'; } else strcpy(dest, src); (where we don't want to take the time to fill the destination with trailing nulls in the "else" case, otherwise we could just use strncpy). That way is: sprintf (dest, "%.*s", n, src); (or if n is known to be, say, 17, then sprintf (dest, "%.17s", src);). In practice this, too, may of course be too slow. But then, so may strcpy(). -- Mark Brader, Toronto "Mark is probably right about something, utzoo!sq!msb, msb@sq.com but I forget what" -- Rayan Zachariassen This article is in the public domain.