Browse Source

better examples section wrt strncpy()

OPENBSD_2_5
millert 25 years ago
parent
commit
7a5b2ea811
1 changed files with 35 additions and 3 deletions
  1. +35
    -3
      src/lib/libc/string/strcpy.3

+ 35
- 3
src/lib/libc/string/strcpy.3 View File

@ -33,7 +33,7 @@
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE. .\" SUCH DAMAGE.
.\" .\"
.\" $OpenBSD: strcpy.3,v 1.3 1998/11/28 14:51:34 espie Exp $
.\" $OpenBSD: strcpy.3,v 1.4 1999/03/05 23:16:05 millert Exp $
.\" .\"
.Dd June 29, 1991 .Dd June 29, 1991
.Dt STRCPY 3 .Dt STRCPY 3
@ -96,16 +96,48 @@ The following sets
to to
.Dq Li abc\e0\e0\e0 : .Dq Li abc\e0\e0\e0 :
.Bd -literal -offset indent .Bd -literal -offset indent
(void)strncpy(chararray, "abc", 6).
(void)strncpy(chararray, "abc", 6);
.Ed .Ed
.Pp .Pp
The following sets The following sets
.Dq Li chararray .Dq Li chararray
to to
.Dq Li abcdef :
.Dq Li abcdef
and does
.Em not
NUL-terminate chararray because the source string is >= the length parameter.
.Fn strncpy
.Em only
NUL-terminates the destination string when then length of the source
string is less than the length parameter.
.Bd -literal -offset indent .Bd -literal -offset indent
(void)strncpy(chararray, "abcdefgh", 6); (void)strncpy(chararray, "abcdefgh", 6);
.Ed .Ed
.Pp
The following copies as many characters from
.Dq Li input
to
.Dq Li buf
as will fit and NUL-terminates the result. Because
.Fn strncpy
does
.Em not
guarantee to NUL-terminate the string itself, we must do this by hand.
.Bd -literal -offset indent
char buf[BUFSIZ];
(void)strncpy(buf, input, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\\0';
.Ed
.Pp
Note that
.Xr strlcpy 3
is a better choice for this kind of operation. The equivalent using
.Xr strlcpy 3
is simply:
.Bd -literal -offset indent
(void)strncpy(buf, input, sizeof(buf));
.Ed
.Sh SEE ALSO .Sh SEE ALSO
.Xr bcopy 3 , .Xr bcopy 3 ,
.Xr memccpy 3 , .Xr memccpy 3 ,


Loading…
Cancel
Save