diff options
author | Ray Lai <ray@cvs.openbsd.org> | 2007-08-08 07:20:46 +0000 |
---|---|---|
committer | Ray Lai <ray@cvs.openbsd.org> | 2007-08-08 07:20:46 +0000 |
commit | 1ef73ccec2927bf811545c08c0f5fe66d0780cff (patch) | |
tree | 0c102b47b69d3082e858566b728e40be602c3daa /lib | |
parent | 93f0a93ea70527771e250436883680a24a846799 (diff) |
Show how to use strcspn(3) to trim newlines.
OK jmc and millert.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/libc/stdio/fgets.3 | 12 | ||||
-rw-r--r-- | lib/libc/string/strcspn.3 | 16 |
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 , |