summaryrefslogtreecommitdiffstats
path: root/lib/libc
diff options
context:
space:
mode:
authorray <ray@openbsd.org>2007-08-08 07:20:45 +0000
committerray <ray@openbsd.org>2007-08-08 07:20:45 +0000
commit1b4e7b486ae7d8fdb8d4712835825e6b3b36bc5d (patch)
tree3c4523e00800a52f979f920a68214094e693839f /lib/libc
parentrealloc can handle NULL values. From Charles Longeau. (diff)
downloadwireguard-openbsd-1b4e7b486ae7d8fdb8d4712835825e6b3b36bc5d.tar.xz
wireguard-openbsd-1b4e7b486ae7d8fdb8d4712835825e6b3b36bc5d.zip
Show how to use strcspn(3) to trim newlines.
OK jmc and millert.
Diffstat (limited to 'lib/libc')
-rw-r--r--lib/libc/stdio/fgets.312
-rw-r--r--lib/libc/string/strcspn.316
2 files changed, 19 insertions, 9 deletions
diff --git a/lib/libc/stdio/fgets.3 b/lib/libc/stdio/fgets.3
index f2d820489f7..da95e9d8fb8 100644
--- a/lib/libc/stdio/fgets.3
+++ b/lib/libc/stdio/fgets.3
@@ -1,4 +1,4 @@
-.\" $OpenBSD: fgets.3,v 1.26 2007/05/31 19:19:31 jmc Exp $
+.\" $OpenBSD: fgets.3,v 1.27 2007/08/08 07:20:45 ray Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
@@ -31,7 +31,7 @@
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
-.Dd $Mdocdate: May 31 2007 $
+.Dd $Mdocdate: August 8 2007 $
.Dt FGETS 3
.Os
.Sh NAME
@@ -211,14 +211,12 @@ if (fgets(buf, sizeof(buf), fp) != NULL) {
If
.Fn strlen
returns 0, the index into the buffer becomes \-1.
-The correct way to trim a newline is shown below.
+One way to concisely and correctly trim a newline is shown below.
.Bd -literal -offset indent
char buf[1024];
-if (fgets(buf, sizeof(buf), fp) != NULL) {
- if (buf[0] != '\e0' && buf[strlen(buf) - 1] == '\en')
- buf[strlen(buf) - 1] = '\e0';
-}
+if (fgets(buf, sizeof(buf), fp) != NULL)
+ buf[strcspn(buf, "\en")] = '\e0';
.Ed
.Sh BUGS
Since it is usually impossible to ensure that the next input line
diff --git a/lib/libc/string/strcspn.3 b/lib/libc/string/strcspn.3
index c5d9e562d25..21c727344dd 100644
--- a/lib/libc/string/strcspn.3
+++ b/lib/libc/string/strcspn.3
@@ -29,9 +29,9 @@
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
-.\" $OpenBSD: strcspn.3,v 1.8 2007/05/31 19:19:32 jmc Exp $
+.\" $OpenBSD: strcspn.3,v 1.9 2007/08/08 07:20:45 ray Exp $
.\"
-.Dd $Mdocdate: May 31 2007 $
+.Dd $Mdocdate: August 8 2007 $
.Dt STRCSPN 3
.Os
.Sh NAME
@@ -72,6 +72,18 @@ size_t span;
span = strcspn(s, charset);
.Ed
+.Pp
+The following removes the first (if any) newline character from string
+.Fa line .
+This is useful for trimming the newline after a
+.Xr fgets 3
+call.
+.Bd -literal -offset indent
+char line[BUFSIZ];
+
+if (fgets(line, sizeof(line), fp) != NULL)
+ line[strcspn(line, "\en")] = '\e0';
+.Ed
.Sh SEE ALSO
.Xr memchr 3 ,
.Xr strchr 3 ,