strncpy

Mark Brader msb at sq.sq.com
Mon Jan 8 17:45:32 AEST 1990


> 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 at sq.com	 but I forget what"	-- Rayan Zachariassen

This article is in the public domain.



More information about the Comp.lang.c mailing list